Getting the value of the JCheckBox parameter

I want to ask if there is a way to get information from JCheckBox without an actionListener. In my code, I look at the file of strings, and in each line there is data which, if selected, should be added to the array in my program. The problem is that I will never know how many JCheckBoxes I will have, it depends on the file.

So my question is how to put the selected rows into an array (or list) by pressing the (ok) button, so that I can do something else with them (in my case, I need to get the data from the file or from and enter it into red-black tree, so I will need to click the highlighted lines on my putDataInTheTree method).

EDIT: Also, is it possible not to show those JCheckBox that have already been added to the program? I.E. if I select a liquid, the next time I call a liquid for the input method, it will not appear in my panel?

Thanks in advance!

What it looks like:

enter image description here

My code 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")); } } 
+4
source share
2 answers

Add your flags to the collection, and when the button is clicked, iterate through the flags and set the text corresponding to each flag:

 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 } 
+8
source

If you save the checkboxes (for example, in the List ), you can iterate over them and ask for your selected state when you click OK.

To get a String from this checkbox, you can select the putClientProperty and getClientProperty , as described in the javadoc JComponent class

+1
source

Source: https://habr.com/ru/post/1446672/


All Articles