简体   繁体   中英

Why are events not posted to AWT EventQueue?

I have the following piece of code

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import javax.swing.*;
class QueueTest {
    public static void main(String[] args) throws InterruptedException, 

InvocationTargetException {
        EventQueue eventQueue = 

Toolkit.getDefaultToolkit().getSystemEventQueue();
        eventQueue.push(new MyEventQueue());


    Frame f=new Frame();
    f.setSize(400,400);
    //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocation(150,150);
    f.setVisible(true);

    Button b=new Button("button");
    f.add(b);

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae)
        {
        System.out.println("button is clicked");
        }
    });
    }

    private static class MyEventQueue extends EventQueue {
        public void postEvent(AWTEvent theEvent) {
//            System.out.println("Event Posted");
  System.out.println("The source of event is "+theEvent.getSource());
            super.postEvent(theEvent);
        }
    }
}

I have written a custom EventQueue . This is working in swing when I've replaced Frame with JFrame and Button with JButton . But why isn't this working for AWT components?

When i have resized the frame, clicked on the button the control is not entered into the postEvent() method. But in swing, it is entered. Why is it so?

Aren't events placed in the EventQueue in AWT? Also who posts the events to this EventQueue ? Windows kernel?

Kindly, reply me.

The AWT events are placed on the queue, but not using the method postEvent . That method exists to allow code outside the AWT to post events. You should have noticed that there are a very little number of events posted that way.

If you override the method protected void dispatchEvent(AWTEvent event) you will see a lot more events, including the Button events.

However, it's not recommended to mess around with the event queue. It will fail once another piece of code pushes a new queue. And it has some other oddities.

If you want to detect ActionEvent s globally, use

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
  public void eventDispatched(AWTEvent event)
  {
    System.out.println("eventDispatched: "+event);
  }
}, AWTEvent.ACTION_EVENT_MASK);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM