[英]Java add ActionListener on a separate class
继承人我想做的事情,其中一个类是包含所有JButtons的JFrame,我想要另一个类来监听在JFrame类上进行的操作。 请参阅以下代码:
public class Frame extends JFrame{
//all the jcomponents in here
}
public class listener implements ActionListener{
//listen to the actions made by the Frame class
}
谢谢你的时间。
只需将侦听器的新实例添加到要侦听的任何组件即可。 任何实现ActionListener
类都可以作为侦听器添加到组件中。
public class Frame extends JFrame {
JButton testButton;
public Frame() {
testButton = new JButton();
testButton.addActionListener(new listener());
this.add(testButton);
}
}
1.你可以使用Inner Class
或Anonymous Inner Class
来解决这个....
例如:
内心阶级
public class Test{
Button b = new Button();
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
// Do whatever you want to do on the button click.
}
}
}
例如:
匿名内在阶级
public class Test{
Button b = new Button();
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// Do whatever you want to do on the button click.
}
});
}
如果您希望同一个listener
实例listener
框架中的所有按钮,则必须使actionPerformed方法根据命令收集所有单击和委托:
public class listener extends ActionListener{
public void actionPerformed(ActionEvent e){
String command = e.getActionCommand();
if (command.equals("foo")) {
handleFoo(e);
} else if (command.equals("bar")) {
handleBar(e);
}
}
private void handleFoo(ActionEvent e) {...}
private void handleBar(ActionEvent e) {...}
}
这将在Java 7中变得更容易,您可以在其中切换字符串! 按钮单击的ActionCommand将是JButton
的Text
-attribute,除非您另外设置它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.