dispatchEvent(AWTEvent) 分派事件

时间:2023-03-09 07:34:29
dispatchEvent(AWTEvent) 分派事件

点一个按钮,显示的分派一个指定的事件给系统。

下面是一个例子,当点击close按钮时,分派一个new WindowEvent(this,WindowEvent.WINDOW_CLOSING)事件给系统,以关闭整个窗口。

/*

通过dispatchEvent(WindowEvent)来显示关闭窗口

*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; public class FrameTest extends JFrame implements ActionListener
{
private JButton close; public FrameTest()
{
super("关闭窗口"); Container c=getContentPane();
c.setLayout(new FlowLayout()); close=new JButton("关闭");
close.addActionListener(this); this.add(close); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,300);
setVisible(true);
} public void actionPerformed(ActionEvent e)
{
Object obj=e.getSource();
if(obj==close)
{
WindowEvent event=new WindowEvent(this,WindowEvent.WINDOW_CLOSING); //下面两种方式都可以
this.dispatchEvent(event); //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
}
} public static void main(String[] args)
{
new FrameTest();
}
}