【问题标题】:detect drag of jframe检测jframe的拖动
【发布时间】:2012-10-11 11:01:47
【问题描述】:

有没有办法在 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() {
}

【问题讨论】:

  • “问题是在 MAX OS X 上,当您停止移动鼠标时,窗口的位置会更新。” 而且..为什么这对您的应用程序来说是个问题.?作为旁白。 1)如果应用程序。正在执行屏幕捕获并且框架显示任何被拖动的视觉迹象,您可能能够分析图像以检测运动。 2) 不可编译的代码应该传达什么?

标签: java macos swing jframe componentlistener


【解决方案1】:

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

所以在你的 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; 
    } 

【讨论】:

    猜你喜欢
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2019-02-22
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多