12day
事件监听
package com.wang.lesson02;
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 myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setBackground(new Color(193, 128, 64));
windowClose(frame);//关闭窗口
}
//关闭事件窗口
public static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
多个按钮只写一个监听类:
package com.wang.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestAction02 {
public static void main(String[] args) {
//两个按钮 实现同一个监听
Frame frame = new Frame("开始-停止");
Button b1 = new Button("start");
Button b2 = new Button("stop");
//可以显示的定义触发会返回的命令,如果不显示定会显示默认的值
//可以多个按钮只写一个监听类
b2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
b1.addActionListener(myMonitor);
b2.addActionListener(myMonitor);
frame.add(b1,BorderLayout.NORTH);
frame.add(b2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
输入框TextFiled监听
package com.wang.lesson02;
import com.sun.media.jfxmedia.events.VideoFrameRateListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestText01 {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyActionListener1 myActionListener1 = new MyActionListener1();
//按下enter就会出发这个输入框的事件
textField.addActionListener(myActionListener1);
//设置替换编码
textField.setEchoChar('*');
setVisible(true);
pack();
}
}
class MyActionListener1 implements ActionListener{

浙公网安备 33010602011771号