Search code examples
javaswingjradiobuttonbuttongroup

Passing JRadioSelection to an ActionLIstener class


For my application, I created two JRadioButton grouped into a "selection" ButtonGroup. I added an ActionListener called "SelectionListener." When I check if my RadioButton is selected using isSelected(), it appears that my selection is not getting passed over to the ActionListener.

public static void main(String[] args) {
    JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment", true);
    JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
    ButtonGroup selection = new ButtonGroup();
    selection.add(monthlyRadioButton);
    selection.add(loanAmountButton);
    monthlyRadioButton.addActionListener(new SelectionListener());
    loanAmountButton.addActionListener(new SelectionListener());
} 

SelectionListener.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class SelectionListener implements ActionListener {
    public void actionPerformed(ActionEvent event){
      if(event.getSource() == monthlyRadioButton)
        System.out.println("You clicked Monthly");
      else
        System.out.println("You clicked Loan Amount");

    }
}

The parameters monthlyRadioButton is not getting passed over to my SelectionListener class. I'm getting an error that it is not being resolved.

How do I pass the monthlyRadioButton in my main method over to my SelectionListener class?


Solution

  • You car retrieve the sender of the event is being handled.

    Something like:

    class SelectionListener implements ActionListener {
        private JComponent monthlyRadioButton;
        private JComponent loanAmountButton;
    
        public SelectionListener(JComponent monthlyRadioButton, JComponent loanAmountButton) {
            this.monthlyRadioButton = monthlyRadioButton;
            this.loanAmountButton = loanAmountButton;
        }
    
        public void actionPerformed(ActionEvent event){
            if(event.getSource() == monthlyRadioButton)
                System.out.println("You clicked Monthly");
            else if(event.getSource() == loanAmountButton)
                System.out.println("You clicked Loan Amount");
        }
    }
    

    On your main method you could instantiate it like:

        monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton));