首页 > 解决方案 > 你如何让 ActionListener 根据 actionPerformed 执行不同的事件?

问题描述

我在四个不同的面板上有四个按钮。如果我按下按钮,我希望它所在的面板改变颜色。问题是我只知道如何为一个按钮而不是全部四个。到目前为止,这是我的代码...

public class tester implements ActionListener
{
JPanel B;
JPanel A;
public static void main(String[]args)
{
    new tester();

}

public void tester()
{
    JFrame test = new JFrame("tester:");
    B = new JPanel();
    A= new JPanel();
    JPanel cc = new JPanel();
    JPanel dd = new JPanel();
    JButton b = new JButton("ButtonB");
    JButton a = new JButton("ButtonA");
    JButton c = new JButton("ButtonC");
    JButton d = new JButton("ButtonD");
    test.setLayout(new GridLayout(2,2));
    test.setSize(600,500);
    B.setBackground(Color.BLUE);
    A.setBackground(Color.RED);
    cc.setBackground(Color.BLACK);
    dd.setBackground(Color.WHITE);
    B.add(b);
    A.add(a);
    cc.add(c);
    dd.add(d);
    test.add(A);
    test.add(B);
    test.add(cc);
    test.add(dd);
    test.setVisible(true);
    b.addActionListener(this);
    a.addActionListener(this);

}
public void actionPerformed(ActionEvent e)
{
    B.setBackground(Color.PINK);
}

}

标签: javaevent-handlingactionlistener

解决方案


You can use anonymously created Action listeners instead of implementing interface in your class.

b.addActionListener(new ActionListener() {
    //method impl.
});

And use that to create 4 different actions.

Or you could get source of action from

e.getSource()

And then decide based on that.

Or you can skip ActionListener all the way, and use lambda

b.addActionListener(e -> someActionOrSomething(e))

推荐阅读