0

I am doing some GUI and I use JCheckBox. I am wondering if this all can be do in an array and loop? It's so tiring to change every single thing.

If you can help me I'd love to hear.

if (box1.isSelected())
    k = 40;
if (box2.isSelected())
    l = 30;
if (box3.isSelected())
    m = 20;
if (box4.isSelected())
    n = 10;
if (box5.isSelected())
    o = 10;
if (box6.isSelected())
    p = 10;
if (box7.isSelected())
    q = 10;
if (box8.isSelected())
    r = 10;
if (box9.isSelected())
    j = 10;
if (box10.isSelected())
    i =10;

s = "Price for this is RM" + 
        (k + l + m + n + o + p + q + r + j + i);

JOptionPane.showMessageDialog(null, s);
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

2

What you probably want is this:

JCheckBox[] checkboxesArray = new JCheckBox[10];
int i, count;

for (i=0; i<10; i++){
    /* display a checkbox... */

/* Finished displaying checkboxes, now you wait for user to finish input... */

for (i=0; i<10; i++){
    if (checkboxesArray[i].isSelected())
        count += 10;
}
s = "Price for this is RM " + count;
JOptionPane.showMessageDialog(null, s);
  • and the input for each box ? where i need to put ? – Lukman Al Hakim Aug 22 '14 at 00:14
  • @LukmanAlHakim: you should display the checkboxes where I put my first `for` loop, see the comments. You can reference them as checkboxesArray[i]. Then you could have something like a button, which, when clicked, would invoke the rest of the code. It's all easy to look up in the docs. –  Aug 22 '14 at 00:16