记忆力再次被折磨,求IDE助攻! ps:顺便复习六级单词。。。
源代码:
import java.awt.event.WindowListener ; import java.awt.event.WindowEvent ; import java.awt.Color ; import javax.swing.JFrame ; class MyWindowEventHandle implements WindowListener { public void windowActivated(WindowEvent e) { System.out.println("windowActivated---->窗口被选中") ; } public void windowClosed(WindowEvent e) { System.out.println("windowClosed---->窗口被关闭") ; } public void windowClosing(WindowEvent e) { System.out.println("windowClosing---->窗口关闭") ; } public void windowDeactivated(WindowEvent e) { System.out.println("windowDeactivated---->取消窗口选中") ; } public void windowDeiconified(WindowEvent e) { System.out.println("windowDeiconified---->窗口从最小化恢复") ; } public void windowIconified(WindowEvent e) { System.out.println("windowIconfied---->窗口最小化") ; } public void windowOpened(WindowEvent e) { System.out.println("WindowOpened---->窗口打开") ; } } ; class Tester { public static void main(String args[]) { JFrame frame = new JFrame("窗口监听") ; frame.addWindowListener(new MyWindowEventHandle()) ; frame.setSize(500,500) ; frame.setBackground(Color.orange) ; frame.setLocation(400,400) ; frame.setVisible(true) ; } }
这样写显然太过冗余,下面介绍窗口监听适配器:如果只需要监听窗口关闭这一个动作,使用接口会造成代码过于冗余,因为要覆写WindowListener各个方法,这里就引出WindowAdapter设计模式,当然可以直接匿名内部类省去创建监听类的麻烦。直接上代码:这样就可以想监听什么就写什么,不需要写一堆冗余代码
import java.awt.event.WindowListener ; import java.awt.event.WindowEvent ; import java.awt.event.WindowAdapter ; //适配器设计模式 import java.awt.Color ; import javax.swing.JFrame ; class Tester { public static void main(String args[]) { JFrame frame = new JFrame("匿名内部类") ; frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println("窗口关闭") ; System.exit(1) ; } } ) ; //匿名内部类配合适配器 frame.setSize(400,400) ; frame.setLocation(400,400) ; frame.setVisible(true) ; } }