事件监听:当某个事件发生的时候,运行程序在干什么。如:点击按钮,输出hello;通过上下左右键控制方向等…
如:按下按钮,输出框输出hello
package 狂神说__Listener;
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 TestActionEvent {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button();
MyActionListener myActeionListener=new MyActionListener();
button.addActionListener(myActeionListener);//需要一个接口
frame.add(button,BorderLayout.CENTER);
frame.setBackground(Color.blue);
frame.setBounds(200,200,600,400);
frame.setVisible(true);
windowsClose(frame);
}
//关闭窗口
private static void windowsClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("hello word!");
}
}
如:输入框的文字被监听,在输入框中输入文字,按下Enter键就会在输入区内输出文本框内容
package 狂神说__Listener;
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 TestAction {
public static void main(String[] args) {
Myframe myframe = new Myframe();
windowsClose(myframe);
}
private static void windowsClose(Myframe frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
static class Myframe extends Frame{
public Myframe(){
TextField textField = new TextField();
this.add(textField);
//监听文本框输入的汉字
MyActionListener1 myActionListener1 = new MyActionListener1();
//按下enter,就会触发输入框事件
textField.addActionListener(myActionListener1);
setVisible(true);
setBounds(300,300,200,200);
}
}
}
class MyActionListener1 implements ActionListener{
@Override
public void actionPerformed(ActionEvent actionEvent) {
//获得资源,返回对象
TextField field=(TextField)actionEvent.getSource();
System.out.println(field.getText());
field.setText("");//Enter键触发后,文本框的内容会被清空
}
}