按钮的监听事件
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ActionListenerTest1 {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button();
/*
addActionListener()这个函数需要传入一个ActionListener
这个ActionListener是继承了EventListener的一个接口
ActionListener里只有一个方法actionPerformed(ActionEvent e)
所以我们自己写一个该接口的实现类,并传入addActionListener()
*/
button.addActionListener(new MyActionListener());
frame.add(button);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
//把关闭frame的事件抽取出来
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了一次");
}
}
运行结果为:
点击一次frame中的button后,控制台打印一句“按钮被点击了一次”
一个类监听多个事件
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionListenerTest2 {
public static void main(String[] args) {
Frame frame = new Frame("开始/停止");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//为按钮设置动作命令
button1.setActionCommand("start");
button2.setActionCommand("stop");
MyActionListener2 myActionListener = new MyActionListener2();
//为按钮添加监听类
button1.addActionListener(myActionListener);
button2.addActionListener(myActionListener);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
//用同一个类去监听两个事件
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//e.getActionCommand()用于获取按钮设置好的动作命令
System.out.println(e.getActionCommand());
}
}
运行的结果为:
点击start按钮,控制台打印start;点击stop按钮,控制台打印stop;
文本框监听事件
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextActionListener {
public static void main(String[] args) {
MyFrame1 myFrame1 = new MyFrame1();
}
}
//把frame的构建拆出来写成一个类,main方法里只负责启动程序,不再写这些样式等等
class MyFrame1 extends Frame{
//重写MyFrame1的构造方法
public MyFrame1(){
TextField textField = new TextField();
/*
MyFrame继承了Frame
所以在给frame添加textfield时不需要再实例化对象以及frame.add
*/
add(textField);
//监听文本框
MyActionListener3 myActionListener3 = new MyActionListener3();
//按下enter就会触发这个文本框的事件
textField.addActionListener(myActionListener3);
//为了实现输入密码时不可见,设置替换编码
textField.setEchoChar('*');
pack();
setVisible(true);
}
}
//创建一个用于监听的类
class MyActionListener3 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
/*
e.getSource()这个函数返回值是一个object,可以向下转型成任何类型
所以这里转型为text类型
*/
e.getSource();//获得一些资源
TextField textField = (TextField) e.getSource();
System.out.println(textField.getText());//得到文本框中的内容并打印
textField.setText("");//为了使输入完成按下回车后文本框内容清空
}
}
运行结果为:
在文本框内输入“内容”二字,显示为**,按下回车后,控制台打印“内容”二字,文本框清空