然后,再在派生类中重载dispatchEvent()方法就可以截获所有的系统事件,包括用户输入事件。下面一段代码给出一个操纵EventQueue的实例:
import java.awt.*; import java.awt.event.*;
public class GenerateEventQueue extends Frame implements ActionListener { Button button1 = new Button(); TextField textField1 = new TextField();
public GenerateEventQueue() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { GenerateEventQueue generateEventQueue = new GenerateEventQueue(); } private void jbInit() throws Exception { button1.setLabel("button1"); button1.addActionListener(this) ; textField1.setText("textField1");
this.add(button1, BorderLayout.SOUTH); this.add(textField1, BorderLayout.CENTER); EventQueue eq=getToolkit().getSystemEventQueue() ; eq.postEvent(new ActionEvent(button1, ActionEvent.ACTION_PERFORMED,"test" )) ; addWindowListener(new WinListener()); setBounds(100,100,300,200); setVisible(true); }
public void actionPerformed(ActionEvent e) { textField1.setText("event is :"+e.getActionCommand()) ; }
}
class WinListener extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0) ; } }
运行结果如下图所示:
|