检测jframe的拖动

时间:2012-10-11 11:01:47

标签: java macos swing jframe componentlistener

有没有办法在拖动时检测JFrame的位置? 问题是,在MAX OS X上,当您停止移动鼠标时,窗口的位置会更新。我看到了计算新位置和设置窗口手册位置的提示。但因此我必须知道我何时开始拖动的位置。 为了使它更清晰一点,JFrame用于捕获屏幕,但是当你移动它时它不会更新,因为它仍然认为它处于旧位置。当你停止移动拖动时(但你仍然可以按住鼠标按钮)然后它会更新。

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 个答案:

答案 0 :(得分:3)

如果你提到的更新仅在窗口停止移动时发生,并且如果知道开始拖动的位置可以真正解决问题,那么我会看到一个选项,您将最后一个位置存储在某个变量中每次检测到移动时都会更新它。

因此,在JFrame类中声明一个私有变量:

Point originLocation = new Point(0,0);

在您的侦听方法中,您可以:

    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; 
    }