您如何让ActionListener根据actionPerformed执行不同的事件?

时间:2018-08-12 17:07:27

标签: java event-handling actionlistener

我在四个不同的面板上分别有四个按钮。如果我按下按钮,我希望面板打开以更改颜色。问题是我只知道如何针对一个按钮而不是全部四个按钮执行此操作。到目前为止,这是我的代码...

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);
}

}

2 个答案:

答案 0 :(得分:1)

您可以使用匿名创建的Action侦听器,而不是在类中实现接口。

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

并使用它来创建4种不同的动作。

或者您可以从

获取行动依据
e.getSource()

然后基于此做出决定。

或者您可以完全跳过ActionListener并使用lambda

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

答案 1 :(得分:0)

您必须检查资源并可以基于该资源执行操作。如果您尝试保留一个常见的ActionListener

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()==b)//button b
        B.setBackground(Color.PINK);
    else if(e.getSource()==a)//button a
        A.setBackground(Color.BLACK);
}

请注意,您必须全局声明按钮,如果必须在类中使用它,

public class Test implements ActionListener
{
JPanel B;
JPanel A;
JButton b;
JButton a;

您还用称为tester的方法创建了实现,该方法应称为

new Test().tester();