首页 > 代码库 > Java Swing界面编程(21)---事件处理:窗口事件

Java Swing界面编程(21)---事件处理:窗口事件

WindowLIstener是专门处理窗口的事件监听窗口。一个窗口的全部变化。如窗口的打开、关闭等都能够使用这个接口进行监听。

实现WIndowListener:

package com.beyole.util;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class MyWindowEventHandle implements WindowListener {

	@Override
	public void windowOpened(WindowEvent e) {
		System.out.println("windowOpened--->窗体被打开");
	}

	@Override
	public void windowClosing(WindowEvent e) {
		System.out.println("windowClosing--->窗体关闭");
	}

	@Override
	public void windowClosed(WindowEvent e) {
		System.out.println("windowClosed--->窗体被关闭");
	}

	@Override
	public void windowIconified(WindowEvent e) {
		System.out.println("windowIconified--->窗体最小化");
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		System.out.println("windowDeiconfied--->窗体从最小化恢复");
	}

	@Override
	public void windowActivated(WindowEvent e) {
		System.out.println("windowActivated--->窗体被选中");
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		System.out.println("windowDeactivated--->取消窗体被选中");
	}

}

单单仅仅有监听器是不够的。还须要在组件使用时注冊监听。这样才干处理,直接使用窗口的addWindowListener(监听对象)方法就可以注冊事件监听

package com.beyole.util;

import java.awt.Color;

import javax.swing.JFrame;

public class MyWindowEventFrame01 {
	public static void main(String[] args) {
		JFrame frame=new JFrame("Crystal");
		frame.addWindowListener(new MyWindowEventHandle());
		frame.setSize(300, 160);
		frame.setBackground(Color.WHITE);
		frame.setLocation(300, 200);
		frame.setVisible(true);
	}
}

程序截图:技术分享

结果截图:技术分享

Java Swing界面编程(21)---事件处理:窗口事件