Getting JCheckBox selected box value - java

I want to ask is there a way to get information from JCheckBox without actionListener. In my code I scan a file of strings and each line has data which, if selected, should be added to an array in my program. Problem is that i will never know how many JCheckBoxes I will have, it depends from file.
So, my question is how to put selected strings to an array (or list) with a press of a button (ok) so i could do something else with them (in my case i need to get data from file or from hand input and put it in a red-black tree, so I will need to push selected strings to my putDataInTheTree method).
EDIT: Also, is it possible not to show those JCheckBoxes that already has been added to the program? I.E. if i choose fluids, next time I call input method fluids wont show in my panel?
Thanks in advance!
How it looks:
My code is so far:
public void input() {
try {
mainWindow.setEnabled(false);
fromFile = new JFrame("Input from file");
fromFile.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
fromFile.setLayout(new BorderLayout());
fromFile.setSize(300,200);
panelFromFile = new JPanel();
panelFromFile.setLayout(new java.awt.GridLayout(0,1));
JScrollPane scrollPane2 = new JScrollPane(panelFromFile);
scrollPane2.setMaximumSize(new Dimension(300, 180));
FileReader File = new FileReader(data);
BufferedReader Buffer = new BufferedReader(File);
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
}
}
ok = new JButton("ok");
ok.addActionListener(this);
fromFile.add(scrollPane2, BorderLayout.CENTER);
fromFile.add(ok, BorderLayout.SOUTH);
fromFile.setLocationRelativeTo(null);
fromFile.setResizable(false);
fromFile.setVisible(true);
}
catch(Exception e) {
text.append("Error in INPUT method");
text.append(System.getProperty("line.separator"));
}
}

Add your checkboxes to a collection, and when the button is pressed, iterate through the checkboxes and get the text associated with each checked checkbox:
private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
...
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
this.checkBoxes.add(check);
}
}
...
public void actionPerformed(ActionEvent e) {
List<String> infos = new ArrayList<String>();
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected() {
infos.add(checkBox.getText());
}
}
// TODO do something with infos
}

If you store the checkboxes (e.g. in a List) you can loop over them and query their selected state when the OK button is pressed.
To obtain the String from the checkbox, you could opt to use the putClientProperty and getClientProperty methods, as explained in the class javadoc of JComponent

Related

Selecting a file, reading through it, and appending its content to 2 linked lists

I'm currently writing a program that should read through a file, go through the file line-by-line, use StringTokenizer to separate the Make (String), Model (String), Year (Integer), and Mileage (Integer), store those values in a Car object (Car(Make, Model, Year, Mileage), in that order), which will then be added as a node to 2 linked lists (one of which sorts by Make and the other doesn't). I successfully did all this and it worked just fine, however, I am now tasked to implement event-driven programming into my existing program (actionListener, JMenuItem, JMenuBar, JMenu, etc.). Before I'd just declare a String object called "file" and set that equal to the file which we're supposed to read from (cars.txt) in the main class, but now I have to add a file menu to the CarGUI to open the file reading. It currently runs but it doesn't display anything in the GUI. One change that I did was make my readFile method accept Files as arguments instead of Strings so that it could be compatible with what's in the FileMenuHandler class.
CarGUI class
This is the class where the JFrame is created and the readFile method exists. This is where the linked lists (SortedCarList and UnSortedCarList) are appended onto the JTextAreas.
public class CarGUI extends JFrame { //CarGUI inherits all the features of JFrame
private JTextArea leftTextArea; //make 2 JTextAreas for the Jframe
private JTextArea rightTextArea;
private StringBuilder leftSide; //make 2 StringBuilders which we'll later use to append the 2 ArrayLists onto
private StringBuilder rightSide;
//Instantiate the two child linked lists we created
static SortedCarList sortedList = new SortedCarList();
static UnsortedCarList unSortedList = new UnsortedCarList();
public CarGUI() //default constructor for the GUI class
{
// Instance variables
this( Project 3 );
}
public CarGUI(String title) //the 1-argument parameter constructor
{
// Call the super class constructor to initialize the super
// class variables before initializing this class's variables
super(title); //Inherited the title from the previous constructor
// Configure the JFrame
// Configure the JFrame components we inherited
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500); //setting the size to an arbitrary width and height
this.setLocation(200, 200);
this.getContentPane().setLayout(new GridLayout(1, 2)); //1 row and 2 columns, where the 2 lists' toStrings can be appended onto
this.getContentPane().setBackground(Color.ORANGE);
this.leftSide = new StringBuilder("Unsorted Cars" + "\n"); //just titling the 2 columns on the JFrame
this.rightSide = new StringBuilder("Sorted Cars" + "\n");
this.leftTextArea = new JTextArea(this.leftSide.toString());
this.rightTextArea = new JTextArea(this.rightSide.toString());
this.getContentPane().add(this.leftTextArea); //add the currently empty TextAreas to the content panes (the left and right ones)
this.getContentPane().add(this.rightTextArea);
//create menu buttons and menu bar
JMenuItem open = new JMenuItem("Open");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem msg = new JMenuItem("Msg");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
FileMenuHandler fmh = new FileMenuHandler(this);
// Add the action listener to the menu items
open.addActionListener(fmh);
quit.addActionListener(fmh);
msg.addActionListener(fmh);
// Add the menu items to the file menu
fileMenu.add(open);
fileMenu.addSeparator();
fileMenu.add(quit);
fileMenu.addSeparator();
fileMenu.add(msg);
// Add file menu to the menu bar, and set this gui's
// menu bar to the menuBar we created above
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.setVisible(true); //without this, the GUI wouldn't even show up
}
//Method that will read from a file, sieve through the lines via the StringTokenizer
//Create Car objects after each line and add them to 2 Linked Lists as CarNodes
//Move on to the next line and keeps going until there are no more tokens to be found in the file
//Then it'll append the lists onto StringBuilders which will then be placed into the textAreas
public void readFile(File file) throws FileNotFoundException{
Scanner scanner = new Scanner(file.getName()); //scanner will now read through the file, whatever it is
String line = scanner.nextLine(); //'line' is assigned to the first line of the file
String delimiter = ",";
StringTokenizer tokenizer = new StringTokenizer(line, delimiter); //tokenizer will go through the line and separate by ","
int tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens and makes tokenCount equal to amount of tokens
while(tokenizer.hasMoreTokens()){ //keeps iterating until there are no more tokens to be found.
//if there aren't exactly 4 tokens, print it to the console
if(tokenCount == 1){ //in the case there's only one text token that can be found
String CarMakeUNO = tokenizer.nextToken();
System.out.println(CarMakeUNO + "\n"); //print to console
}
if(tokenCount == 2){ //in the case there are two tokens that were found in the current line
String CarMakeDOS = tokenizer.nextToken();
String CarModelDOS = tokenizer.nextToken();
System.out.println(CarMakeDOS + ", " + CarModelDOS + "\n"); //print to console
}
else if(tokenCount == 3){ //in the case there are three tokens that were found, doing this just in case another .txt file is used
String CarMakeTRES = tokenizer.nextToken();
String CarModelTRES = tokenizer.nextToken();
int CarYearTRES = Integer.parseInt(tokenizer.nextToken());
System.out.println(CarMakeTRES + " " + CarModelTRES + " " + CarYearTRES + "\n"); //print to console
}
//finally, if there are 4 tokens in the current line, use tokenizer to extract the Make, Model, Year, and Mileage and put them into a new Car Object
else if (tokenCount == 4){ //since the Make, Model, Year, and Mileage are in fixed order, we can just do it by each subsequent token:
String CarMake = tokenizer.nextToken();
String CarModel = tokenizer.nextToken();
int CarYear = Integer.parseInt(tokenizer.nextToken()); //since years are integers, we need to parse it with parseInt
int CarMileage = Integer.parseInt(tokenizer.nextToken());
//make a new object with the above values
//newCar(Make, Model, Year, Mileage);
Car newCar = new Car(CarMake, CarModel, CarYear, CarMileage); //put the appropriate variables in the newly instantiated Car object
unSortedList.addIt(newCar); //place the Car object into the linked list as a node
sortedList.insert(newCar);
}//goes through a single line of the file
if(scanner.hasNextLine()){ //if there are more lines in the file
line = scanner.nextLine(); //assigns string line to the next line of the file/goes to the next line
tokenizer = new StringTokenizer(line, delimiter); //StringTokenizer tokenizes the current line
tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens of the new line
}
}//end of while loop (stops when no more tokens)
scanner.close(); //close the scanner since it's not necessary anymore
leftSide.append(unSortedList.toString()); //adds the LinkedLists to their respective StringBuilder
rightSide.append(sortedList.toString()); //Utilizes the overrided toString in CarList
//adds the 2 StringBuilders to the 2 JTextAreas
this.leftTextArea.setText(this.leftSide.toString());
this.rightTextArea.setText(this.rightSide.toString());
}
}// end of CarGUI
This is my FileMenuHandler class, which handles the actionListener (makes the JMenuItems behave like we want). It calls the readFile method from the CarGUI class which the selected file (fc.getSelectedFile) is the argument of.
public class FileMenuHandler implements ActionListener
{
//this code is fine
// Save the reference to the GUI object this FileMenuHandler is
// associated with
private CarGUI gui;
// Constructor that takes as its parameter the GUI associated
// with this FileMenuHandler
public FileMenuHandler(CarGUI gui)
{
this.gui = gui;
}
public void actionPerformed(ActionEvent event)
{
// Get the command name from the event
String menuName = event.getActionCommand();
if (menuName.equals("Open")) //if Open is selected
{
// Create the object that will choose the file
JFileChooser fc = new JFileChooser();
// Attempt to open the file
int returnVal = fc.showOpenDialog(null);
// If user selected a file, create File object and pass it to
// the gui's readFile method
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
try {
this.gui.readFile(file); //calls readFile method in CarGUI class
} catch (FileNotFoundException e) {
System.out.println(" There is no file");
e.printStackTrace();
}
}
else if (returnVal == JFileChooser.CANCEL_OPTION)
{
System.out.println("Open command cancelled by user.");
}
}
else if (menuName.equals("Quit")) //if Quit is selected
{
System.exit(1); //end the program
}
else if (menuName.equals("Msg")) //if Msg is selected
{
JOptionPane.showMessageDialog(null, "You clicked on \'Msg\'"); //display this message
}
}
}
This is my main class
public class Project3 {
public static void main(String arg[]) throws FileNotFoundException{ //main method that enables us to even run this class
CarGUI testGUI = new CarGUI(); //create a new CarGUI object
}
}
I tried to annotate it as much as I could. It returns 2 nulls in the place where the linked lists are supposed to be displayed.
Okay. I solved the problem. It wasn't reading because I put .getName in file in my readFile method... hahahaha. It's working just fine now!

Conversion of String to JComboBox

How do I convert string to JComboBox object model ?
Note: Im using NetBeans IDE 8.0.2
to change JComboBox from <String> to <Object>
right click on JComboBox and select properties
select code tab
click on ... button from type parameters
replace <String> to <Object> and click ok.
You don't convert a String to a ComboBoxModel. You add the String to the combo box or the ComboBoxModel.
For example:
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.add( "One" );
comboBox.add( "Two" );
comboBox.add( "Three" );
Read the section from the Swing tutorial on How to Use Combo Boxes for more information and other examples.
You can also search the forum or web for other examples.
I solved the problem.
I needed to be able to grab each line independent of the other so I can use just one Text file but break it out to different j combo boxes. Below was what I did. Is there a shorter way of doing this? I will have 20 JComboBox with each having around 7 select entries. The entries for the drop down boxes are around 50 lines of selections.
public void inputFile() throws IOException{
//File reader method
FileReader file = new FileReader("c:\\jcboEntries.dat");
try (BufferedReader br = new BufferedReader(file)) {
String[] lines = new String [6];
String [] jcbo = new String [6];
try {
int i =0;
lines[0] = br.readLine();
jcbo[0] = lines[0];
jcbo0 = jcbo[0];
jcboNUMONE.addItem(jcbo0);
System.out.println(jcbo0);
lines[1] = br.readLine();
jcbo[1] = lines[1];
jcbo1 = jcbo[1];
jcboNUMONE.addItem(jcbo1);
System.out.println(jcbo1);
lines[2] = br.readLine();
jcbo[2] = lines[2];
jcbo2 = jcbo[2];
jcboNUMONE.addItem(jcbo2);
System.out.println(jcbo2);
lines[3] = br.readLine();
jcbo[3] = lines[3];
jcbo3 = jcbo[3];
jcboNUMONE.addItem(jcbo3);
System.out.println(jcbo3);
lines[4] = br.readLine();
jcbo[4] = lines[4];
jcbo4 = jcbo[4];
jcboNUMONE.addItem(jcbo4);
System.out.println(jcbo4);
lines[5] = br.readLine();
jcbo[5] = lines[5];
jcbo5 = jcbo[5];
jcboNUMONE.addItem(jcbo5);
System.out.println(jcbo5);
} catch (IOException e){}
} catch (IOException e){}
}

How to display the next text lines once user presses the next button?

I am trying to create a program which allows the user to choose a text file
from their directory. That then gets displayed in a JTextArea within the Frame created using Swing.
I've created a button with a action command that's supposed to allow the user once pressed to get the next text lines from the file, displayed within the text area until it reaches the end of file.
To do that I used the sub-string command to go through the String variable and display it .
But it seems to not to do that instead it just displays all the text found within the file.
Below you will find the code that allows the program to open the file and display as well
as the buttons created to aid in navigating through the text.
package reader;
public class Viewer extends JFrame{
private static final long serialVersionUID = 1L;
private static JFrame Frame;
private JPanel Cpanel;
JScrollPane scrollPane;
String book = "";
int currentChar = 10;
static JTextArea textArea;
JFileChooser fileChooser;
File f;
public static void DocViewer() {
new Viewer("new document");
}
public Viewer(String s) {
Frame = new JFrame("Reader");
textArea = new JTextArea(20,60);
textArea.setFont(new Font("Calibri", Font.PLAIN, 12));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
f = new File("C://Program Files//Java//jdk1.6.0//bin//");
fileChooser = new JFileChooser(f);
Frame.getContentPane().setBackground(Color.red);
Frame.setLayout(new GridLayout(3, 1));
Cpanel = new JPanel();
Cpanel.setLayout(new FlowLayout());
Cpanel.setBackground(Color.RED);
JButton StButton = new JButton("open");
JButton QButton = new JButton("back");
JButton TestButton = new JButton("next");
TestButton.setHorizontalTextPosition(SwingConstants.LEFT);
StButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String book = "";
// int currentChar=10;
int returnVal = fileChooser.showOpenDialog(Viewer.this);
try {
File file = fileChooser.getSelectedFile();
FileInputStream fin = new FileInputStream(file);
BufferedReader d = new BufferedReader(
new InputStreamReader(fin, "UTF-8"));
book = "";
if (returnVal == JFileChooser.APPROVE_OPTION) {
while (book != null) {
book = d.readLine();
textArea.append(book + "\n");
System.out.println(book);
}
}
System.out.println("returnVal = " + returnVal
+ " and ba.fileChooser.APPROVE_OPTION = "
+ JFileChooser.APPROVE_OPTION);
fin.close();
} catch (Exception ex) {
}
}
});
QButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.exit(0);
Viewer.EXIT_ON_CLOSE();
Loader.main(null);
}
});
TestButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String page = "";
for (int l = 1; l >= 10; l = l + 2) {
page += book.substring(l, l + 49);
page += "\n";
currentChar += 50;
}
}
});
Cpanel.add(StButton);
Cpanel.add(QButton);
Cpanel.add(TestButton);
Frame.add(Cpanel, BorderLayout.NORTH);
Frame.add(scrollPane, BorderLayout.CENTER);
Frame.setSize(300,300);
Frame.setVisible(true);
}
}
Your code is only doing what you tell it to do.
Your button's ActionListener has a while loop that loops through the entire file writing all the contents to the JTextArea. So I'm not sure why this behavior surprises you.
If it were me, I'd read the entire file into an ArrayList<String> with each new line being added one at a time. I'd do this once, perhaps in a class constructor if you know what file to read in advance, perhaps in response to getting a File via a JFileChooser if you don't.
Then in my button grab the next line in this List, using an int index variable to store the index number, and append this line to my JTextArea.
Maybe even better than using a JTextArea would be to use a JList.
Done.
Edit
You've asked more questions, so I'll try to subdivide the steps a little:
Create an ArrayList<String> as an instance field (non-static class variable)
Open your file put it into a Scanner object
Using a while loop, loop while the Scanner has a next line
Inside the loop, use the Scanner to grab the next line and put it into the List.
Also give the class an int index field.
On button push, get the String in the ArrayList corresponding to the index, and then increment the index
Publish that String in your JTextField using its append method.
If still stuck, break down your steps even further and try to find specifically where you're stuck. Google for a solution, and if still stuck, come here with your specific question and code.
Check the java info resources. In particular look at the Beginner's resources for links.
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter.

Populating a JTable with parsed information

I am trying to populate a JTable with information taken from a website (namely price and item name). I have a class that asks the user to input a URL and scans the page for the price and item name as well as the URL. Currently it takes all the parsed information and stores it in three different text files, one for price, one for item name, and one for the URL. I am trying to populate a JTable containing three columns (item name, price, and URL) with this information but every time I scan a new page the text files are overwritten and the previous information is lost. I don't necessarily need the JTable to be populated via the text file, I just need it to somehow get the information. Here is some of my code.
public BestBuy (JFrame frame){
super (frame, "Best Buy URL", true);
setLayout (new FlowLayout());
label = new JLabel ("Enter Best Buy URL");
add (label);
url = new JTextField ("Enter URL Here", 40);
add (url);
submit = new JButton ("Submit");
add (submit);
event b = new event ();
submit.addActionListener (b);
}
public class event implements ActionListener{
public void actionPerformed (ActionEvent b){
try {
String datab = url.getText(); //perform your operation
datab = datab.trim();
datab = datab.toLowerCase();
Document document = Jsoup.connect(datab).get();
String amountb = document.select(".amount").first().text();
String nameb = document.select(".product-title").first().text();
FileWriter stream = new FileWriter ("C:\\Users\\Daniel\\Desktop\\price.txt");
BufferedWriter out = new BufferedWriter (stream);
out.write(amountb + "\n");
out.newLine();
out.close();
FileWriter stream1 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\itemName.txt");
BufferedWriter out1 = new BufferedWriter (stream1);
out1.write(nameb + "\n");
out1.newLine();
out1.close();
FileWriter stream2 = new FileWriter ("C:\\Users\\Daniel\\Desktop\\url.txt");
BufferedWriter out2 = new BufferedWriter (stream2);
out2.write(datab + "\n");
out2.newLine();
out2.close();
}
catch (Exception ex) {
}
setVisible (false);
}
This class asks the user for a Best Buy URL and parses the given page for item name, and price then writes it to files on my desktop.
public FirstGui (){
setLayout (new FlowLayout ());
String[] columnName = {"Item Name", "Price", "URL"};
Object [] [] data = {
};
table = new JTable (data, columnName);
table.setPreferredScrollableViewportSize(new Dimension (500, 300));
table.setFillsViewportHeight (true);
JScrollPane scrollpane = new JScrollPane (table);
add (scrollpane);
Now I am trying to get that parsed information onto my JTable but I have no idea how to do so. I tried to do
public getdatab() {
return datab;
}
public getnameb() {
return nameb;
}
public getamountb() {
return amountb;
}
but all these strings are within a void so that did not work. As you can probably see I am quite new to java and this might have an obvious solution but I have been stuck on this for a few days and cant figure it out. Thank you.
I'm not sure exactly how your getting your data, but you want to do something like this. Since you're trying to write the data to three different files, I will assume the data is coming in from three different streams. Here's the thing though. For this to work, all the data needs to be in parallel, Meaning that the first item, should correspond to the first price and first url, and so on. If this is the case, you can do something like this.
Have three separate lists.
List<String> names = new ArrayList<String>();
List<String> prices = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
Then for each item you were going to add to a file, add to the list instead.
Use a DefaultTableModel as the model of your JTable
String[] columnName = {"Item Name", "Price", "URL"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
Now you can just add rows, using the data from the lists. Use the method model.addRow(row), where row is an array of Objects
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
String price = prices.get(i);
String url = urls.get(i);
model.addRow(new Object[] { name, price, url });
}
That's all there is to it. The model will update the table for you dynamically. But remember, like I said, the data in the lists must be in sync with one another for you to get the desired result.
If you're getting data in one row at a time, instead of one column at a time, that makes it even easier. For each set of data, that comes in, just add it as a row like it did in step 5.

Is a text file in Java a GUI

Is it right to think that when you create a text file in Java, you are essentially creating a text file like the one that appears with programs like notepad?
I have a JComboBox menu with various selections. I also created a text file and had it so that the user selection will be written in the text file. So the question is, how can I have this text file that I've created to appear? (as a GUI or any other way...)
My Code:
static JFrame frame;
FileWriter f;
BufferedWriter bw;
int myAge;
String myStringAge;
for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel modelAge = new DefaultComboBoxModel();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox ageEntries = new JComboBox();
ageEntries.setModel(modelAge);
//Add ItemListener
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener {
public void itemStateChanged(ItemEvent event){
myAge = (Integer) event.getItem();
myStringAge = Integer.toString(myAge);
try {
bw.write(myStringAge);
bw.close();
} catch (Exception e){
}
}
A text file is not a GUI. Use JTextArea to display text. Have a look at http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
You can do so using JEditorPane. You might want to create a new JFrame for it. Don't forget to setContentType() to "text/plain". Then you can just create a FileReader for your file and pass it to the editor pane throught the read() method.
Start with Basic I/O. That should answer your question (and the next 9).

Categories