java - 如何在 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);
}
});
}
}
输出:
对于控制台输出,只需更新al_2
withSystem.out...
而不是tf TextField
推荐阅读
- android - 如何测量手机上直接内存访问(DMA)的次数?
- amazon-ecs - ECS 计划任务的每周计划表达式
- python - 使用 tf.reduce_mean 替代全局池?
- python - Visual Studio代码将文件保存在脚本以外的另一个目录中
- php - PHP 返回错误:BookinginfoController.php 第 101 行中的 ErrorException:遇到非数字值
- c# - 无法将类型 string[] 隐式转换为模型
- c# - C# 如何让其他变量与 char 数组配合,以便我可以使用 char 查找字母出现的次数
- cakephp - 来自不同数据源的具有相同表名的 CakePHP 3 烘焙模型
- html - 如何使用 $emit 在 angularjs 中与父控制器通信
- c# - 在 Sqlite 数据库 Unity 中保存为 4 位数字的系统日期