gpt4 book ai didi

java - Java 中两个类之间的事件处理程序

转载 作者:行者123 更新时间:2023-12-01 14:07:47 24 4
gpt4 key购买 nike

我有兴趣从另一个类获取由多个组件生成的 ActionEvent...请帮助。下面给出了示例。

class MyFrame {
public MyFrame() {
JFrame window = new JFrame();
Container c = window.getContentPane();
c.setLayout(new BorderLayout());
JButton btn1 = new JButton("Save");
JButton btn2 = new JButton("Delete");
c.add(btn1);
c.add(btn2);
EventHandler handler = new EventHandler();
btn1.addActionListener(handler);
btn2.addActionListener(handler);
.................
}
}
class EventHandler implements ActionListener {
public void actionPerformed(ActionEvent ae)
{
// what can i do here to get Event and also recognized which component fired event?
// I have used getSource(). but problem is not solved.
if ( ae.getSource() == btnSave)
{
}
}
}

请尽快帮助我...

最佳答案

一般来说,如果你有多个JButton,你可以为每个组件设置操作命令

...
btn1.addActionListener(handler);
btn1.setActionCommand("save");
btn2.addActionListener(handler);
btn2.setActionCommand("delete");
...

在处理程序中你可以获得操作命令

class EventHandler implements ActionListener {

public void actionPerformed(ActionEvent ae){
String actionCommand = ((JButton) ae.getSource()).getActionCommand();

if (actionCommand.equals("save")) {
...
}else if (actionCommand.equals("delete") {
...
}
}
}

关于java - Java 中两个类之间的事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18760566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com