我正在尝试在数组中搜索已选中的复选框。然后我需要选中所选的复选框并将它们放入一个字符串中以向用户显示他们选择的内容(可能是一个Dialog弹出框)。在经过大量试验和错误之后,我不知道使用什么语法来实现这个或方法。
复选框:
JCheckBox s1 = new JCheckBox("Mowing",false);
JCheckBox s2 = new JCheckBox("Edging",false);
JCheckBox s3 = new JCheckBox("Trimming",false);
JCheckBox s4 = new JCheckBox("Blowing",false);
JCheckBox s5 = new JCheckBox("Mulch",false);
JCheckBox s6 = new JCheckBox("Hedges",false);
JCheckBox s7 = new JCheckBox("Pruning Trees", false);
JCheckBox s8 = new JCheckBox("Landscaping",false);
JCheckBox s9 = new JCheckBox("Weeding", false);
JCheckBox s10 = new JCheckBox("Leaf Removal", false);
使用if语句检查复选框的数组和for循环
JCheckBox[] boxes = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10};
int count = 0;
int i;
//String for checked boxes to be put into
String requested = " ";
for(i = 0; i < boxes.length; ++i)
{
if(boxes[i].isSelected())
{
requested = boxes[i].getText();
++count;
//Add the checked boxes to a string. This is where I am stuck
}
}
答案 0 :(得分:2)
也许只是做
requested += boxes[i].getText() + " ";
或使用StringBuilder:
StringBuilder sb = new StringBuilder();
for (i = 0; i < boxes.length; ++i) {
...
sb.append(boxes[i].getText() + " ");
...
}
答案 1 :(得分:1)
您只需使用JOptionPane
作为弹出窗口即可。希望这可以帮到你!
JOptionPane.showMessageDialog(this,"requested ="+ requested);