0

对于我的应用程序,我创建了两个JRadioButton分组为“选择” ButtonGroup。我添加了一个ActionListener名为“SelectionListener”。当我检查是否RadioButton使用isSelected()选择了 my 时,似乎我的选择没有传递给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());
} 

选择监听器.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");

    }
}

参数monthlyRadioButton没有传递给我的SelectionListener班级。我收到一个错误,它没有得到解决。

如何将我的monthlyRadioButton主要方法传递给我的SelectionListener班级?

4

3 回答 3

3

您的汽车检索正在处理的事件的发送者。

就像是:

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

在您的主要方法上,您可以像这样实例化它:

    monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton));
于 2012-06-21T18:13:50.953 回答
1

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

于 2012-06-21T18:16:23.147 回答
1

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.

于 2012-06-21T18:16:48.997 回答