窗体触发事件之焦点以及状态转换

来源:互联网 发布:淘宝如何关键词优化 编辑:程序博客网 时间:2024/06/07 01:17
import java.awt.Frame;import java.awt.event.WindowEvent;import java.awt.event.WindowFocusListener;import java.awt.event.WindowStateListener;import javax.swing.JFrame;class WindowStateListener_Example extends JFrame{public WindowStateListener_Example(){//构造方法super();addWindowStateListener(new MyWindowStateListener());}private class MyWindowStateListener implements WindowStateListener{public void windowStateChanged(WindowEvent e){int oldState=e.getOldState();//旧状态int newState=e.getNewState();//新状态String from="";//标识窗体以前状态的字符串的String to="";switch(oldState){case Frame.NORMAL:from="正常化";break;case Frame.MAXIMIZED_BOTH:from="最大化";break;default:from="图表化";}switch(newState){case Frame.NORMAL:to="正常化";break;case Frame.MAXIMIZED_BOTH:to="最大化";break;default:to="图标化";}System.out.println(from+"------->"+to);}}}public class WindowFocusListener_example extends JFrame{public static void main(String[] args) {WindowFocusListener_example frame=new WindowFocusListener_example();WindowStateListener_Example f=new WindowStateListener_Example();frame.setVisible(true);f.setVisible(true);}public WindowFocusListener_example(){super();addWindowFocusListener(new MyWindowFocusListener());//为窗体添加焦点事件监听器setTitle("捕获窗体焦点事件");setBounds(100,100,500,375);//设置位置和大小setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}   class MyWindowFocusListener implements WindowFocusListener{public void windowGainedFocus(WindowEvent e){//窗口获得焦点时触发System.out.println("窗口获得了焦点");}public void windowLostFocus(WindowEvent e){System.out.println("窗口失去了焦点");}}} 

原创粉丝点击