java - 你如何让 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);
}
}
解决方案
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))
推荐阅读
- python - 如何使用 CSS 选择器使用 BeautifulSoup 检索特定链接?
- openssl - Nextcloud 客户端构建需要 P12_KEY_PASSWORD
- javascript - 如何在不使用 Larastan 的情况下在 Laravel8 中运行 PHPSTAN?
- html - reactjs - 如何将html元素从子元素传递给父元素?
- javascript - 打字稿:“访问类实例属性时,此条件将始终返回'false'”
- django - 如何将外键字段呈现给 Django 表单,就像它在管理面板上显示的那样(内联字段)?
- javascript - 将插入符号放置到 contenteditable div 的下一个孩子
- node.js - 使用LinkedIn API节点js上传图片
- flutter - 在 SingleChildScrollView 中使用展开的网页浏览
- salesforce - 用于拨打外线电话的 Salsforce 和 Plivo 集成