我认为您可以扩展自己的JCheckBox
(比如说JCheckBoxWithID
),让您保留 id。然后在List
每次使用ItemListener选中/取消选中复选框时使用 a 来存储/删除 id
这样,您将避免重复checkboxPanel
询问谁被选中并保持分离的职责:
JCheckBox
只显示一个关键字并持有一个 id
List
只存储选定的 ID
ItemListener
当 a 被选中/取消选中时处理事件JCheckBox
,并将其 id 添加到/从中删除List
希望这个例子有帮助:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Tests {
private void initGUI(){
/* This list will store selected ids */
final List<Integer> selectedIds = new ArrayList<>();
ItemListener itemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBoxWithID){
JCheckBoxWithID checkBoxWithID = (JCheckBoxWithID) e.getSource();
if(checkBoxWithID.isSelected()){
selectedIds.add(checkBoxWithID.getId());
} else {
selectedIds.remove(checkBoxWithID.getId());
}
}
}
};
String[] keyWords = new String[]{"Help 1", "Help 2", "Help 3", "Help 4", "Help 5", "Help 6"};
Integer id = 0;
JPanel checkBoxesPanel = new JPanel(new GridLayout(3,3));
/* Add many checkbox as you keywords you have */
for(String keyWord : keyWords){
JCheckBoxWithID checkBoxWithID = new JCheckBoxWithID(keyWord, id);
checkBoxWithID.addItemListener(itemListener);
checkBoxesPanel.add(checkBoxWithID);
id++;
}
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, Arrays.toString(selectedIds.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);
}
});
JPanel content = new JPanel(new FlowLayout(FlowLayout.LEADING));
content.add(checkBoxesPanel);
content.add(submit);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Tests().initGUI();
}
});
}
class JCheckBoxWithID extends JCheckBox {
/* I use Integer but the id could be whatever you want, the concept is the same */
private Integer _id;
public JCheckBoxWithID(String text, Integer id) {
super(text);
_id = id;
}
public void setId(Integer id){
_id = id;
}
public Integer getId(){
return _id;
}
}
}
这是一个打印屏幕: