Reputation: 63
I am trying to search an array for check boxes that have been checked. Then I need to take the checked boxes that are selected and put them into a string to show the user what they have selected(maybe into a Dialog popup box). I don't know what syntax to use for this or method to do this after a lot of trial and error I have come here.
Check boxes:
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);
Array and for loop with an if statement to check for checked boxes
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
}
}
Upvotes: 0
Views: 49
Reputation: 4953
You can simply use JOptionPane
for your popup window. Hope this can help you!
JOptionPane.showMessageDialog(this,"requested ="+ requested);
Upvotes: 1
Reputation: 82461
It's relatively easy in java 8:
String delimiter = " ";
String s = Arrays.stream(boxes)
.filter((b) -> b.isSelected()) // restrict to selected
.map((b)->b.getText()) // get text for each element
.collect(Collectors.joining(delimiter)); // join the strings
Upvotes: 1
Reputation: 1352
Maybe just do
requested += boxes[i].getText() + " ";
Or using StringBuilder:
StringBuilder sb = new StringBuilder();
for (i = 0; i < boxes.length; ++i) {
...
sb.append(boxes[i].getText() + " ");
...
}
Upvotes: 2