detect drag of jframe

3.8k views Asked by At

Is there a way to detect the position of a JFrame while it's dragged? The problem is that on MAX OS X the position of a window updates when you stop moving the mouse. I saw a tip of calculating the new position and setting the position of the window manual. But therefore i have to know the position of when i started dragging. To make it a bit more clear, the JFrame is used to capture the screen, but when you move it around it doesn't update cause it still think it's at the old position. When you stop moving the dragging (but you can still hold the mouse button) then it updates.

import java.awt.event.ComponentListener;
import java.awt.Component;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;

void setup() {
  frame.addComponentListener(new ComponentListener() 
  {  
    public void componentMoved(ComponentEvent evt) {
      Component c = (Component)evt.getSource();
      println("moved "+frameCount);
    }

    public void componentShown(ComponentEvent evt) {}

    public void componentResized(ComponentEvent evt) {}

    public void componentHidden(ComponentEvent evt) {}
  }
  );
}

void draw() {
}
1

There are 1 answers

0
AudioBubble On

If what you mentioned regarding the update happening only when the window has stopped moving, and if knowing the position of when you started dragging can really solve the issue, then I see an option that you store the last location in some variable and update it each time you detect a move.

So declare a private variable in your JFrame class:

Point originLocation=new Point(0,0);

in your listener method you can:

    public void componentMoved(ComponentEvent evt) {
          Component c = (Component)evt.getSource();
          Point currentLocationOnScreen=c.getLocationOnScreen();

 // do your requirements here with the variables currentLocationOnScreen and originLocation

          // update the originLocation variable for next occurrences of this method 
          originLocation=currentLocationOnScreen; 
    }