我有兴趣从另一个类中获取由多个组件生成的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)
{
}
}
}
请尽快帮助我......
答案 0 :(得分:1)
通常,如果您有多个JButton,则可以为每个组件设置action命令
...
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") {
...
}
}
}
答案 1 :(得分:0)
尝试
JButton temp = (JButton) ae.getSource();
if(temp.getText().equals("Save")) {
...
}
另一种方法是使用EventHandler参数化构造函数传递按钮引用,然后将其添加为侦听器:
EventHandler handler = new EventHandler(btn1, btn2);
btn1.addActionListener(handler);
btn2.addActionListener(handler);
然后修改EventHandler类:
class EventHandler implements ActionListener {
JButton b1, b2;
public EventHandler(JButton b1, JButton b2) {
this.b1 = b1;
this.b2 = b2;
}
public void actionPerformed(ActionEvent ae)
{
JButton temp = (JButton) ae.getSource();
if(temp == b1)
{
...
}
...
}
}
答案 2 :(得分:0)
您可以在ActionEvent
here上阅读,了解如何处理它。
获取由另一个类的多个组件生成的ActionEvent
您希望事件处理程序知道它来自哪个?
为此你可以做到
JButton temp = (JButton) ae.getSource();
按照建议然后使用
获取按钮文本temp.getText();
如果没有按钮的实例,则将其与按钮的文本进行比较。如果你只是比较两个