2012-06-21 62 views
0

对于我的应用程序,我创建了两个分组为“选择”ButtonGroupJRadioButton。我添加了一个名为“SelectionListener”的ActionListener。当我检查是否使用​​选择了我的RadioButton时,看起来我的选择没有传递到ActionListener将JRadioSelection传递给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"); 

    } 
} 

参数monthlyRadioButton没有获得通过到我SelectionListener类。我收到一个错误,说它没有被解决。

如何将我的主要方法中的monthlyRadioButton传递给我的SelectionListener类?

+0

为了将来的参考,你应该在你的问题中包含确切的错误信息。我读了整件事情,而且从来没有清楚你在这里有一个编译器错误。包括这些信息将帮助我们更快地回答您的问题。 –

回答

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

我试过这个,但我的每月RadioButton和loanAmountButton给我一个错误,说这两个不能解决。 – Huy

+0

请尝试修改后的样本... –

+0

Money ... Stackoverflow积分为您服务!感谢Spaeth的帮助。 – Huy

1

您创建main命名为monthlyRadioButton(thius一个新的变量是本地main,由不可见其他地方),但请检查另一个(未在您的代码中列出)actionPerformed

+0

我把它移到我的主要方法之外,但我仍然遇到同样的问题。 'public static JRadioButton monthlyRadioButton = new JRadioButton(“Monthly Payment”,true);' 'public static JRadioButton loanAmountButton = new JRadioButton(“Loan Amount”);'' – Huy

1

在选择单选按钮之前调用在JRadioButton上注册的。这就是为什么你的​​调用返回false(或者更确切地说:他们返回实际值,在更改之前)。

如果你想处理状态变化,你应该注册一个ChangeListener