Search code examples
javaswingjcheckbox

Java, If multiple checkboxes are ticked?


I'm creating a simple program where the user can tick checkboxes for different colors. If several boxes are ticked then it should show what the mix of the colors are going to be. Example blue and yellow is ticked then the label shows green. I got 3 problems.

  1. Checking multiple colors dont mix like the above example.
  2. Unchecking a checkbox dont change the label.
  3. When all of them are uncheck it should go back to "No colors chosen".

class LabDemo extends JFrame implements ActionListener {
    JLabel displayColor = new JLabel("No chosen color");
    JCheckBox blue = new JCheckBox("Blue");
    JCheckBox yellow = new JCheckBox("Yellow");
    JCheckBox red = new JCheckBox("Red");
    JPanel panel = new JPanel();

    public LabDemo() {
        panel.setLayout(new GridLayout(4,1));
        blue.addActionListener(this);
        yellow.addActionListener(this);
        red.addActionListener(this);
        this.add(panel);
        displayColor.setBackground(Color.WHITE);
        panel.add(blue); panel.add(yellow); panel.add(red); panel.add(displayColor);
        setSize(300,300);
        setLocation(100,100);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (blue.isSelected()) {
            displayColor.setText("Blue");
            panel.setBackground(Color.BLUE);
        }
        else if (yellow.isSelected()) {
            displayColor.setText("Yellow");
            panel.setBackground(Color.YELLOW);
        }
        else if (red.isSelected()) {
            displayColor.setText("Red");
            panel.setBackground(Color.RED);
        }
        else if (blue.isSelected() && yellow.isSelected()) {
            displayColor.setText("Blue + Yellow = Green");
            panel.setBackground(Color.GREEN);
        }
    }
}


Solution

  • You will never enter in the last case (blue and yellow), because you are in an if-else, and one of the above statements will be evaluated true before that (the blue one alone, in this case). If the cases are just those four, the "blue and yellow" one should be put at the first thing to check.