0

私のアプリケーションではJRadioButton、「選択」にグループ化された2つを作成しましたButtonGroupActionListener「SelectionListener」という名前を追加しました。RadioButtonを使用して自分が選択されているかどうかを確認isSelected()すると、選択がに渡されていないよう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解決されていないというエラーが表示されます。

monthlyRadioButtonmainメソッドのを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

mainnamedに新しい変数を作成しますmonthlyRadioButton(thius は にローカルでmain、他の場所からは見えません)。actionPerformed

于 2012-06-21T18:16:23.147 に答える
1

ラジオ ボタンが選択される前に、登録された が呼び出されますactionListenersJRadioButtonそのため、isSelected()呼び出しが返さfalseれます (より正確には、変更前の実際の値が返されます)。

状態の変化を処理したい場合は、ChangeListener.

于 2012-06-21T18:16:48.997 に答える