Java Swing Tutorial - Java EventQueue.isDispatchThread()








Syntax

EventQueue.isDispatchThread() has the following syntax.

public static boolean isDispatchThread()

Example

In the following code shows how to use EventQueue.isDispatchThread() method.

import java.awt.AWTEvent;
import java.awt.EventQueue;
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;
/*w w w .  j  av a  2 s.c om*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel implements ActionListener {
  Main() {
    JButton button = new JButton("Click to chooose the first point");
    add(button);
    button.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
    Graphics g = getGraphics();
    Point p = getClick();
    g.drawOval(p.x - 2, p.y - 2, 4, 4);
    Point q = getClick();
    g.drawOval(q.x - 2, q.y - 2, 4, 4);
    g.drawLine(p.x, p.y, q.x, q.y);
    g.dispose();
  }
  public Point getClick() {
    EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
    System.out.println(eq.isDispatchThread());
    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) {
      }
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.setVisible(true);
  }

}