我有四个按钮,每个按钮在四个不同的面板上。如果我按下按钮,我会希望面板上的颜色改变。问题是我只知道怎么做一个按钮,而不是所有四个按钮。这是我到目前为止的代码。
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);
}
}
发布于 2018-08-13 01:16:59
如果你试图保持一个通用的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();
发布于 2018-08-13 01:14:30
您可以使用匿名创建的Action侦听器,而不是在类中实现接口。
b.addActionListener(new ActionListener() {
//method impl.
});
并用它来创建4个不同的动作。
或者你可以从
e.getSource()
然后在此基础上做出决定。
或者,您可以完全跳过ActionListener,而使用lambda
b.addActionListener(e -> someActionOrSomething(e))
https://stackoverflow.com/questions/51811034
复制相似问题