3

I have two JRadioButton with ImageIcon for each one. Because of the ImageIcons I'm using, I need to give the appearance that one button is selected and the other one is not selected. To do this I'm trying to disable the other button, which automatically changes the ImageIcon to disabled appearance.

Problem is that when I click on the disabled JRadioButton, nothing happens, not even the ActionListener on the JRadioButton is getting called.

Is there a way to enable a disabled JRadioButton by clicking directly on it? Once it's disabled, it's ActionListener no longer gets called, so I can't enable it by clicking on it.

Basically I'm trying to give the appearance that when one is selected, the other is not selected, using ImageIcons.

//Below part of my code how I initialize the buttons
ButtonGroup codeSearchGroup = new ButtonGroup();

searchAllDocs = new JRadioButton(new ImageIcon(img1));
searchCurrDoc = new JRadioButton(new ImageIcon(img2));

RadioListener myListener = new RadioListener();
searchAllDocs.addActionListener(myListener);
searchCurrDoc.addActionListener(myListener);

codeSearchGroup.add(searchAllDocs);
codeSearchGroup.add(searchCurrDoc);


//Below listener class for buttons
class RadioListener implements ActionListener {  
    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == searchAllDocs){
            searchAllDocs.setEnabled(true);
            System.out.println("Search All documents pressed. Disabling current button...");
            searchCurrDoc.setEnabled(false);

        } 
        else{
            searchCurrDoc.setEnabled(true);
            System.out.println("Search Current document pressed. Disabling all button...");
            searchAllDocs.setEnabled(false);
        }
    }


}

Thanks in advance.

Marquinio
  • 4,601
  • 13
  • 45
  • 68

1 Answers1

4

The ActionListener wont fire in disabled mode, but mouse events will.

Thus simply add a MouseAdapter to JRadioButton and override mouseClicked(..) and call setEnable(true) within overridden method like so:

    JRadioButton jrb = new JRadioButton("hello");
    jrb.setEnabled(false);

    jrb.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent me) {
            super.mouseClicked(me);
            JRadioButton jrb = (JRadioButton) me.getSource();
            if (!jrb.isEnabled()) {//the JRadioButton is disabled so we should enable it
                //System.out.println("here");
                jrb.setEnabled(true);
            }
        }
    });

though I must say there is a bit of skewed logic at play. If something is disabled its done so for a reason, thus we shouldnt allow users to be able to enable. and if we do there should be a control system where we can choose to have the button enabled/disable it wouldnt become the control system itself.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138