2012-06-21 63 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