4

私がやりたいことは次のとおりです。クラスの 1 つは、すべての JButton を含む JFrame 用です。別のクラスに、JFrame クラスで行われたアクションをリッスンさせたいと考えています。以下のコードを参照してください。

public class Frame extends JFrame{
    //all the jcomponents in here

}

public class listener implements ActionListener{
    //listen to the actions made by the Frame class

}

御時間ありがとうございます。

4

3 に答える 3

6

聞きたいコンポーネントにリスナーの新しいインスタンスを追加するだけです。実装するクラスはすべてActionListener、リスナーとしてコンポーネントに追加できます。

public class Frame extends JFrame {
    JButton testButton;

    public Frame() {
        testButton = new JButton();
        testButton.addActionListener(new listener());

        this.add(testButton);
    }
}
于 2012-08-09T17:18:44.323 に答える
3

1.Inner Classまたはを使用して、Anonymous Inner Classこれを解決できます....

例えば:

内部クラス

public class Test{

 Button b = new Button();


 class MyListener implements ActionListener{

       public void actionPerformed(ActionEvent e) {

                    // Do whatever you want to do on the button click.
      } 

   }
}

例えば:

匿名内部クラス

public class Test{

     Button b = new Button();

     b.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

                        // Do whatever you want to do on the button click.
          } 


   });

    }
于 2012-08-09T17:35:36.953 に答える
1

フレーム内のすべてのボタンをリッスンするの同じインスタンスが必要listenerな場合は、すべてのクリックを収集し、コマンドに基づいて委譲する actionPerformed メソッドを作成する必要があります。

public class listener extends ActionListener{
    public void actionPerformed(ActionEvent e){
        String command = e.getActionCommand();
        if (command.equals("foo")) {
            handleFoo(e);
        } else if (command.equals("bar")) {
            handleBar(e);
        }
    }

    private void handleFoo(ActionEvent e) {...}
    private void handleBar(ActionEvent e) {...}
}

これは、文字列を切り替えることができる Java 7 でより簡単になります! ボタン クリックの ActionCommand は、別の方法で設定しない限り、 のText-attribute になります。JButton

于 2012-08-09T19:28:34.293 に答える