GUI学习之窗口监听
写小游戏里面窗口监听的应用比较少
package lesson3; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import static com.sun.glass.ui.Cursor.setVisible; public class TestWindow { public static void main(String[] args) { } } class WindowFrame extends Frame { public WindowFrame(){ setBackground(Color.pink); setBounds(100,100,200,200); setVisible(true); //addWindowListener(new MyWindowListener()); this.addWindowListener( //匿名内部类 new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.out.println("你点击了×"); } } ) } } class MyWindowListener extends WindowAdapter{ @Override public void windowClosing(WindowEvent e) { setVisible(false);//隐藏窗口,通过按钮,隐藏窗口 System.exit(0);//0正常退出,非正常退出是1 } } }
重新写下方法
package lesson3; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class TestWindow { public static void main(String[] args) { new WindowFrame(); } } class WindowFrame extends Frame { public WindowFrame(){ setBackground(Color.pink); setBounds(100,100,200,200); setVisible(true); //addWindowListener(new MyWindowListener()); this.addWindowListener( //匿名内部类 new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { System.out.println("opened"); } @Override public void windowClosing(WindowEvent e) { System.out.println("closing"); } @Override public void windowClosed(WindowEvent e) { System.out.println("closed"); System.exit(0); } //窗口激活 @Override public void windowActivated(WindowEvent e) { WindowFrame source=(WindowFrame)e.getSource(); source.setTitle("被激活了"); System.out.println("Activated"); } @Override public void windowDeactivated(WindowEvent e) { super.windowDeactivated(e); } @Override public void windowIconified(WindowEvent e) { super.windowIconified(e); } @Override public void windowDeiconified(WindowEvent e) { super.windowDeiconified(e); } @Override public void windowStateChanged(WindowEvent e) { super.windowStateChanged(e); //状态改变,从激活到另外的一个状态 } @Override public void windowGainedFocus(WindowEvent e) { super.windowGainedFocus(e); } @Override public void windowLostFocus(WindowEvent e) { super.windowLostFocus(e); } } ); } }
内部类,打开窗口,窗口激活,关闭窗口,窗口输出closing,打开窗口之后,窗口被激活,可以重置窗口名称