Search code examples
javaswingjcomboboxjradiobutton

Deselected JRadioButton


The code I'm creating involves a JRadioButton and a JComboBox. I want the JComboBox to be enabled if the JRadioButton is selected and disabled if it's not selected or deselected. My problem is that the JComboBox won't be disabled if I deselect the JRadioButton. How can I do this? Here's my code

    LouisClub=new JComboBox();
    LouisClub.setEnabled(false);

    LouisClub.addItem("Writer");
    LouisClub.addItem("Photojournalist");
    LouisClub.addItem("Cartoonist");
    LouisClub.addItem("Layout Artist");

    Louis=new JRadioButton("The Louisian");

    Louis.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            LouisClub.setEnabled(true);
        }
    });

Solution

  • You should JCheckBox instead of JRadioButton for such things and then you need check for checkBox status in actionPerformed() method and based on that enable/disable comboBox. Something like

    Louis=new JCheckBox();
    Louis.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           LouisClub.setEnabled(((JCheckBox)e.getSource()).isSeleted());
        }
    }
    

    Also it might be good (Not sure) to use ChangeListener instead of ActionListener.

        Louis.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent ce) {
                 LouisClub.setEnabled(((JCheckBox)ce.getSource()).isSeleted());
            }
        });