[英]How to Listen two separate buttons in Java AWT?
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}
在上面我想添加另一个按钮并添加 ActionListener 并定义actionPerformed
方法,但该方法只需要在终端中打印 hello。
我会为此做些什么?
也许这会很有用。
主要是需要为每个按钮添加单独的侦听器。(也可以使用相同的侦听器,但需要过滤来自事件的来源,以便为每个按钮执行不同的操作)
它还针对关闭事件进行了更新。 但最好尝试查看JFrame(Swing)
,因为Frame
非常古老。 无论如何,主要原则是相同的。
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ALTest {
public static void main(String[] args) {
Frame f = new Frame("ActionListener Example");
final TextField tf = new TextField();
tf.setBounds(50, 50, 150, 20);
Button b = new Button("Button_1");
b.setBounds(50, 100, 60, 30);
Button b2 = new Button("Button_2");
b2.setBounds(150, 100, 60, 30);
f.add(b);
f.add(b2);
ActionListener al_1 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tf.setText("B1 : " + e.getActionCommand());
}
};
ActionListener al_2 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tf.setText("B2 : " + e.getActionCommand());
}
};
b.addActionListener(al_1);
b2.addActionListener(al_2);
f.add(tf);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// close frame
f.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
}
}
Output:
对于控制台 output,只需使用 System.out 更新al_2
System.out...
而不是tf TextField
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.