5

ActionListenerボタンのグループにを追加したいと思います。ボタンをラップするクラスはありますか? オブジェクトのようなもの、GroupJButtonsまたはより一般的なグループの何か? ActionListenerそのため、それらすべてに を設定できます。結局のところ、どのボタンが押されたかはあまり気にしません。彼のテキストを変更したいだけなので、それを a にキャストしてJButtonテキストを変更するだけです。

プロセス全体でコード行を 1 行または 2 行に減らすことができますが (ループを使用する場合)、論理的に優れているので、それを行いたいと考えています。

4

2 に答える 2

7

この場合、AbstractActionクラスを拡張して、同じアクションを多くのボタンに適用することができます。

  class MyAction extends AbstractAction {
       public MyAction(String text, ImageIcon icon,
                  String desc, Integer mnemonic) {
       super(text, icon);
       putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
   }
   public void actionPerformed(ActionEvent e) {
        //do the action of the button here
    }
  }

次に、同じことを実行したいボタンごとに、次のことができます。

 Action myAction = new MyAction("button Text", anImage, "Tooltip Text", KeyEvent.VK_A);
 button = new JButton(myAction);
于 2012-12-09T14:44:23.133 に答える
4

これを使用して各ボタンを作成できます

private JButton createButton(String title, ActionListener al) {
    JButton button = new JButton(title);
    button.addActionListener(al);
    return button;
}

そして、これはアクションを処理するために

public void actionPerformed (ActionEvent ae) {
    JButton button = (JButton)ae.getSource();
    button.setText("Wherever you want");
}
于 2012-12-09T14:41:57.917 に答える