如何在Java Swing中为多个按钮添加多个ActionListener

Jav*_*its 5 java swing

我知道如何为它创建一个按钮和一个动作监听器.但是我希望它们有几个按钮和actionListeners,它们可以执行彼此无关的单独操作.

例:

protected JButton x;

x = new JButton("add");
x.addActionListener(this);

public void actionPerformed(ActionEvent evt) { //code.....}
Run Code Online (Sandbox Code Playgroud)

现在我想要其他按钮可能有不同的功能,如减法,乘法等,请建议.谢谢

oli*_*olz 11

关于什么:

    JButton addButton = new JButton( new AbstractAction("add") {
        @Override
        public void actionPerformed( ActionEvent e ) {
            // add Action
        }
    });

    JButton substractButton = new JButton( new AbstractAction("substract") { 
        @Override
        public void actionPerformed( ActionEvent e ) {
            // substract Action
        }
    });
Run Code Online (Sandbox Code Playgroud)


Liv*_*Liv 7

使用内部类:

x = new JButton("add"); 
x.addActionListener(
  new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      //your code here
    }
  }
);
Run Code Online (Sandbox Code Playgroud)


fmu*_*car 6

您可以使用它ActionEvent.getSource()来决定来源并采取相应的行动,也可以ActionListeners为每个来源定义不同的来源.


小智 6

怎么样...

protected JButton x, z, a, b,c;

x = new JButton("add x");
z = new JButton("add z");
a = new JButton("add a");
b = new JButton("add b");
c = new JButton("add c");
x.addActionListener(this);
z.addActionListener(this);
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
Run Code Online (Sandbox Code Playgroud)

然后

public void actionPerformed(ActionEvent evt)
{
     if (evt.getSource()==x)
         {
            //do something
         }
     else if (evt.getSource()==z)
         {
            //do something
         }
     else if (evt.getSource()==a)
         {
            //do something
         }
     else if (evt.getSource()==b)
         {
            //do something
         }
     else if (evt.getSource()==c)
         {
            //do something
         }
}
Run Code Online (Sandbox Code Playgroud)

这总是对我有用,但老实说,我不确定这是否不是坏习惯