Use the Event queue to retrieve event : Event Queue « Event « Java






Use the Event queue to retrieve event

Use the Event queue to retrieve event
  
import java.awt.AWTEvent;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class EventQueuePanel extends JPanel implements ActionListener {
  EventQueuePanel() {
    JButton button = new JButton("Draw line");
    add(button);
    button.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
    Graphics g = getGraphics();

    displayPrompt(g, "Click to chooose the first point");
    Point p = getClick();
    g.drawOval(p.x - 2, p.y - 2, 4, 4);
    displayPrompt(g, "Click to choose the second point");
    Point q = getClick();
    g.drawOval(q.x - 2, q.y - 2, 4, 4);
    g.drawLine(p.x, p.y, q.x, q.y);
    displayPrompt(g, "Done! Press button the start again.");
    g.dispose();
  }

  public void displayPrompt(Graphics g, String s) {
    y += 20;
    g.drawString(s, 0, y);
  }

  public Point getClick() {
    EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
    while (true) {
      try {
        AWTEvent evt = eq.getNextEvent();
        if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
          MouseEvent mevt = (MouseEvent) evt;
          Point p = mevt.getPoint();
          Point top = getRootPane().getLocation();
          p.x -= top.x;
          p.y -= top.y;
          return p;
        }
      } catch (InterruptedException e) {
      }
    }
  }

  private int y = 60;
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("EventQueueTest");
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    Container contentPane = frame.getContentPane();
    contentPane.add(new EventQueuePanel());

    frame.show();
  }

}

           
         
    
  








Related examples in the same category

1.Event object has information about an event, that has happened.
2.Register several listeners for one event.
3.ActionEvent.getActionCommand()
4.Adding an InputMap to a Component
5.Event source and listener
6.Multiple sources: A listener can be plugged into several sources.
7.Using an inner ActionListener class.
8.void java.awt.Toolkit.addAWTEventListener(AWTEventListener listener, long eventMask)
9.int java.awt.event.WindowEvent.WINDOW_OPENED
10.JComponent.WHEN_IN_FOCUSED_WINDOW
11.Register action
12.Using EventQueue.invokeLater to start a Swing application