本文共 2833 字,大约阅读时间需要 9 分钟。
1.添加 窗口事件监听器: addWindowListener( new 自定义的窗口监听器对象
2.自定义 窗口监听器类,此类要实现一个java awt窗口监听器的接口( 名为WindowListener )
WindowListener 监听器接口:
*:这个接口必须把它所规定的六个抽象方法都实现了,分别是:
1.窗口被打开时触发:
windowOpened(WindowEvent e)
2.点击窗口右上角的 × 时触发:
windowClosing(WindowEvent e)3.窗口真正被关闭时触发:
void windowClosed(WindowEvent e)
4.窗口被最小化时触发:
windowIconified(WindowEvent e)5.窗口从最小化恢复时触发:
windowDeiconified(WindowEvent e)6.窗口失去焦点时触发:(失去焦点指 该窗口不再是现在正在 操作的窗口)
windowDeactivated(WindowEvent e)7.窗口获得焦点时触发:
windowActivated(WindowEvent e)例子:
import java.awt.Frame;import java.awt.TextArea;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class Windows { private Frame f = new Frame("test windows"); private TextArea ta = new TextArea(6,40); //文本框 public void init() { f.addWindowListener(new MyListener()); //添加窗口监听器 f.add(ta); f.pack(); f.setVisible(true); } /*自定义窗口监听器*/ class MyListener implements WindowListener { public void windowOpened(WindowEvent e) { ta.append("窗口打开"); ta.append("\n"); } public void windowClosing(WindowEvent e) { ta.append("窗口关闭ing"); ta.append("\n"); System.exit(0); } public void windowClosed(WindowEvent e) { ta.append("窗口关闭了ed"); ta.append("\n"); } public void windowIconified(WindowEvent e) { ta.append("窗口最小化"); ta.append("\n"); } public void windowDeiconified(WindowEvent e) { ta.append("窗口恢复"); ta.append("\n"); } public void windowActivated(WindowEvent e) { ta.append("窗口被激活"); ta.append("\n"); } public void windowDeactivated(WindowEvent e) { ta.append("窗口失去焦点"); } } public static void main(String[] args) { new Windows().init(); }}
使用事件适配器版本:
WindowAdapter
1.用了适配器后,就不需要像上述代码(通过实现监听器接口)那样,要手动实现接口的全部方法2.只需要实现自己需要的方法即可,其余方法适配器会自动给它空实现(即什么都不做)
public class Windows { private Frame f = new Frame("test windows"); private TextArea ta = new TextArea(6,40); //文本框 public void init() { f.addWindowListener(new MyListener()); //添加窗口监听器 f.add(ta); f.pack(); f.setVisible(true); } /*自定义窗口监听器*/ public class MyListener extends WindowAdapter //让监听器直接继承适配器 { public void windowClosing(WindowEvent e) //自定义的windowClosing方法 { ta.append("Close Window"); System.exit(0); } public void windowOpened(WindowEvent e) //自定义WindowOpened的方法 { ta.append("open Window"); } } public static void main(String[] args) { new Windows().init(); }}
使用适配器+匿名内部类版本(代码更简洁了)
public class Windows { private Frame f = new Frame("test windows"); private TextArea ta = new TextArea(6,40); //文本框 public void init() { f.addWindowListener(new WindowAdapter() //匿名内部类。一次性的匿名类继承WindowAdapter适配器类,实现了windowClosing()方法 { public void windowClosing(WindowEvent e) { System.out.println("close window"); System.exit(0); } } ); //添加窗口监听器 f.add(ta); f.pack(); f.setVisible(true); } public static void main(String[] args) { new Windows().init(); }}
转载地址:http://dwbh.baihongyu.com/