如果有30个复选框,我不想要检查超过6个。我有一个int跟踪检查了多少。每个框都有一个项侦听器,它调用一个方法来查看该int的位置,如果它达到6,则该方法在每个框上调用setEnabled(false)。 但是,即使在int number_of_boxes_checked达到6之后,这些框也不会被禁用。
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;
}
}
}
答案 0 :(得分:1)
在1
方法中,您需要limit_checkBoxes()
,而不是循环中的i < 30
。请参阅我的嵌入式评论。
i > 30
答案 1 :(得分:0)
使用此for (int i = 0; i > 30; ++i) {
for (int i = 0; i < 30; i++) {