码迷,mamicode.com
首页 > 其他好文 > 详细

dispatchEvent(AWTEvent) 分派事件

时间:2015-06-17 12:54:56      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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

下面是一个例子,当点击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();
  }
}

  

dispatchEvent(AWTEvent) 分派事件

标签:

原文地址:http://www.cnblogs.com/personnel/p/4582769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!