GUIp7-8
事件监听
- 某件事发生时需要做什么
package tcf; 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 Test1 { public static void main(String[] args) { //按下按钮,触发某些事件 Frame frame = new Frame(); Button button = new Button(); //addActionListener()需要一个ActionListener,所以需要构造一个ActionListener MyActionListener myActionListener = new MyActionListener(); button.addActionListener(myActionListener); frame.add(button, BorderLayout.CENTER); //frame的大小会被设置为最佳大小,也就是prefrredSize frame.pack(); windowClose(frame); frame.setVisible(true); } //关闭窗体的事件 private static void windowClose(Frame frame) { frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } //事件监听 class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println("aaa"); } }
用MyMonitor实现两个按钮一起监听
package GUI.lee.test; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Demo3 { public static void main(String[] args) { Frame frame = new Frame(); Button button = new Button("start"); Button button1 = new Button("stop"); //给button设置信息,可以替换掉默认值触发返回的信息 button1.setActionCommand("button1-stop"); MyMonitor myMonitor = new MyMonitor(); button.addActionListener(myMonitor); button1.addActionListener(myMonitor); frame.add(button, BorderLayout.SOUTH); frame.add(button1, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); } } class MyMonitor implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println("msg:"+e.getActionCommand()); } }
输入框TextField监听
package GUI.lee.test; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Demo4 { public static void main(String[] args) { new MyFrame01(); } } class MyFrame01 extends Frame{ public MyFrame01(){ //单行文本域 TextField textField = new TextField(); add(textField); //监听这个文本框输入的文字 MyActionListener myActionListener = new MyActionListener(); //按enter会触发输入框事件 textField.addActionListener(myActionListener); //设置替换编码,密码遮盖会用到 textField.setEchoChar('*'); setVisible(true); pack(); } } class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { TextField field = (TextField) e.getSource();//获得一些资源,返回的一个对象 System.out.println(field.getText());//获得输入框中的文本 field.setText("");//回车后文本框“清空” } }