質問

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?

役に立ちましたか?

解決

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));

他のヒント

You create a new variable in main named monthlyRadioButton (thius is local to main, not visible from anywhere else), but check another (not listed in your code) in actionPerformed

The actionListeners registered on JRadioButton are called before the radio button becomes selected. That is why your isSelected() invocations return false (or to be more precise: they return the actual value, before the change).

If you want to handle state changes, you should register a ChangeListener.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top