按钮监听
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("button");
button.setBounds(11,11,11,11);
//因为addActionListener()需要一个ActionListener所以我们要构造一个ActionListener。
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
WindowsClose(frame);//窗口关闭事件
frame.add(button);
frame.setVisible(true);
frame.setBounds(222,222,222,222);
}
//窗口关闭事件
private static void WindowsClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//ActionListener事件监听
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
按钮监听事件共用
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestActionTwo extends TestActionEvent {
public static void main(String[] args) {
//实现两个按钮实现同一个监听
//开始 停止
Frame frame = new Frame("start-stop");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//可以显示的定义除法会返回的命令,否则返回默认的Label
button2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.setBounds(300,300,300,300);
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("start"))
System.out.println("点击了开始:"+e.getActionCommand());
else System.out.println("点击了停止:"+e.getActionCommand());
}
文本框 TestField 监听事件
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestText01 {
public static void main(String[] args) {
//启动!
new MyFrame();
}
}
class MyFrame extends Frame{
public MyFrame(){
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyActionListener2 myActionListener = new MyActionListener2();
//按下enter就会触发这个输入框的事件
textField.addActionListener(myActionListener);
//设置密码文本
textField.setEchoChar('*');
pack();
setVisible(true);
}
}
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField source =(TextField) e.getSource();//获得一些资源、返回的一个对象
System.out.println(source.getText());//获得输入框的文本。
source.setText("");
}
}