简体   繁体   English

一个用于许多JButton的ActionListener

[英]One ActionListener for many JButtons

I would like to add an ActionListener to a group of buttons. 我想将ActionListener添加到一组按钮。 Is there any class that wrap the buttons? 是否有任何类包裹按钮? Something like GroupJButtons or something more generally group of objects? GroupJButtons这样的东西还是更普遍的一组对象? so I can set an ActionListener to all of them. 所以我可以为所有这些设置一个ActionListener After all I don't really care which buttons is pressed I just want to change his text so all I need to do is casting it to a JButton and changing the text. 毕竟我并不关心按哪个按钮我只想更改他的文本所以我需要做的就是将它转换为JButton并更改文本。

The whole process would reduce the code lines in 1 or 2 (in case you use a loop) but I want to do that since it sounds logically better. 整个过程会减少1或2中的代码行(如果你使用循环)但我想这样做,因为它听起来逻辑上更好。

In this case you can extend the AbstractAction class and simply apply the same action to many buttons. 在这种情况下,您可以扩展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
    }
  }

Then for each button that you want the same thing to happen you can: 然后,对于您希望发生相同事情的每个按钮,您可以:

 Action myAction = new MyAction("button Text", anImage, "Tooltip Text", KeyEvent.VK_A);
 button = new JButton(myAction);

You can use this to create each button 您可以使用它来创建每个按钮

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

And this to process the action 这就是处理行动

public void actionPerformed (ActionEvent ae) {
    JButton button = (JButton)ae.getSource();
    button.setText("Wherever you want");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM