Search code examples
javaswingradio-buttonawtmixing

Common Action Listener for 3 Buttons


I am having trouble with the design of my code. I have 3 buttons not in a button group. I want to - based on the selected button - perform an action. Now the action requires a modification of an object in the class. This means i cannot use an inner class because this does not have access to the outer. If i could add an event listener to a button group this would be much easier but as i see it i will need an event handler for each radio button, is this correct? If not how else can i do it? Thanks

A quick example

public class Test(){
    RadioButton 1 = new RadoButton();
    RadioButton 2 = new RadoButton();
    RadioButton 3 = new RadoButton();
    Object myObject = new Object();

   public void clickEvent(){
       if(1.isSelected()){
           myObject.doOne();
       }else if(2.isSelected()){
           myObject.doTwo();
       }.....
   }
}

Solution

  • You can set the same listener to all your buttons.

    Pseudo code:

    radioButton1 = new RadioButton();
    radioButton2 = new RadioButton();
    radioButton3 = new RadioButton();
    
    listener = new ActionListener() {
    ...
    }
    
    
    radioButton1.addActionListener(listener);
    radioButton2.addActionListener(listener);
    radioButton3.addActionListener(listener);