If have 30 checkboxes and I don't want more than 6 of them to be checked. I have an int keeping track of how many are checked. Each box has an item listener which calls a method to see what that int is at, and if it reaches 6, the method calls the setEnabled(false) on each box. However, even after the int number_of_boxes_checked reaches 6 the boxes don't get disabled.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import java.awt.GridLayout;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JLabel;
public class JLottery2 extends JFrame {
private JPanel contentPane;
int number_of_boxes_checked = 1;
JCheckBox[] checkBox = new JCheckBox[30];
JLabel label = new JLabel("0");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JLottery2 frame = new JLottery2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JLottery2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 586, 360);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 321, 299);
contentPane.add(panel);
panel.setLayout(new GridLayout(5, 6, 0, 0));
JPanel panel_1 = new JPanel();
panel_1.setBounds(330, 11, 230, 299);
contentPane.add(panel_1);
panel_1.add(label);
for (int i = 0; i < 30; ++i) {
checkBox[i] = new JCheckBox(Integer.toString(i + 1));
panel.add(checkBox[i]);
}
for (int i = 0; i < 30; ++i) {
checkBox[i].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
limit_checkBoxes();
}
});
}
}
public void limit_checkBoxes() {
label.setText(Integer.toString(number_of_boxes_checked));
if (number_of_boxes_checked > 6) {
for (int i = 0; i > 30; ++i) {
checkBox[i].setEnabled(false);
}
} else {
++number_of_boxes_checked;
}
}
}
In your
limit_checkBoxes()
method, you wanti < 30
, noti > 30
in the loop. See my embedded comment.