DarkKnight
DarkKnight

Reputation: 243

How to simulate JDialog movement in JFC

I have a JDialog being displayed on screen and I want to simulate its movement (Drag from one location to another) based on a condition. Is there any way this can be done ?

Upvotes: 0

Views: 125

Answers (1)

Dan D.
Dan D.

Reputation: 32391

See this piece of code below. I have just tested it and it works fine. It is just a proof of concept.

private void startDialog() {
  final JDialog d = new JDialog(this, "Test", true);
  d.getContentPane().add(new JLabel("Something"));
  d.setBounds(100, 100, 400, 300);
  Thread t = new Thread(new Runnable() {
    public void run() {
      for (int i = 0; i < 50; i++) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            Point p = d.getLocation();
            d.setLocation(p.x + 10, p.y + 10);
          }
        });
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          // ignore
        }
      }
    }
  });
  t.start();
  d.setVisible(true);
}

You can improve the code yourself:

  • use a Timer instead of a regular Thread
  • tweak the sleep times and the location jumps and so on

Just call this method from any Swing application and it will work.

Upvotes: 3

Related Questions