2012-11-17 111 views
4

我想问的是有没有从JCheckBox获取信息的方式没有actionListener。在我的代码中,我扫描了一个字符串文件,并且每行都有数据,如果选中的话,应该将其添加到我的程序中的数组中。问题是我永远不知道有多少JCheckBoxes,它取决于文件。因此,我的问题是如何通过按下按钮(确定)将选定的字符串放入数组(或列表),所以我可以做他们的其他事情(在我的情况下,我需要从文件或从手工输入并将其放在红黑树中,所以我需要将选定的字符串推送到我的putDataInTheTree方法中)。获取JCheckBox选择的框值

编辑:另外,是否有可能不显示那些已经添加到程序的JCheckBoxes? I.E.如果我选择液体,下次我打电话输入法液体不会显示在我的面板?

在此先感谢!

如何看起来:

enter image description here

我的代码是迄今:

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")); 
    } 
} 

回答

8

你的复选框添加到一个集合,并按下按钮时,遍历复选框,并得到与每个选中的复选框关联的文本:

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 
} 
+0

感谢解释,帮助了很多:) –

1

如果您存储复选框(例如在List)你可以循环它们并在按下OK按钮时查询它们的选择状态。

为了从复选框String,你可以选择使用putClientPropertygetClientProperty方法,如在JComponent类Javadoc