0

プログラムに複数のチェックボックスがあります。ユーザーに 3 つのチェックボックスのみを選択してもらいたいのですが、そのうちの 3 つがチェックされている場合は、他のチェックボックスを無効にする必要があります。さらに、1 つがチェックされていない場合は、他のすべてを有効にする必要があります。

4

3 に答える 3

2

以下は、ほぼ完全なソース コードを含むソリューションです。

public class TestProgram {

    public static JCheckBox[] checkList = new JCheckBox[10];

    public static void main(String[] args) {

        Listener listener = new Listener();

        for (int i = 0; i < 10; ++i) {
            checkList[i] = new JCheckBox("CheckBox-" + i);
            checkList[i].addItemListener(listener);
        }

        //
        // The rest of the GUI layout job ...
        //
    }

    static class Listener implements ItemListener {

        private final int MAX_SELECTIONS = 3;

        private int selectionCounter = 0;

        @Override
        public void itemStateChanged(ItemEvent e) {
            JCheckBox source = (JCheckBox) e.getSource();

            if (source.isSelected()) {
                selectionCounter++;
                // check for max selections:
                if (selectionCounter == MAX_SELECTIONS)
                    for (JCheckBox box: checkList)
                        if (!box.isSelected())
                            box.setEnabled(false);
            }
            else {
                selectionCounter--;
                // check for less than max selections:
                if (selectionCounter < MAX_SELECTIONS)
                    for (JCheckBox box: checkList)
                        box.setEnabled(true);
            }
        }
    }
}
于 2014-02-03T06:52:21.437 に答える