简体   繁体   English

Java jLabel从Netbeans“事件”上下文菜单中拖放

[英]Java jLabel drag and drop from netbeans “events” context menu

I'm trying to drag a jLabel around the screen following the mouse pointer. 我正在尝试将jLabel跟随鼠标指针拖到屏幕周围。 As I am no expert on GUI programming I'm trying to do it using Netbeans' GUI design facilities. 因为我不是GUI编程的专家,所以我尝试使用Netbeans的GUI设计工具来实现。

I click on "events-mousemotion-mousedragged" and then insert the following code: 我单击“ events-mousemotion-mousedragged”,然后插入以下代码:

private void jLabel2MouseDragged(java.awt.event.MouseEvent evt) {                                     
  int x=evt.getX();
  int y=evt.getY();

  jLabel2.setLocation(x, y);
  jLabel2.repaint();  }  

I don't expect this simple piece of code to work marvels, the issue however is that it behaves in an erratic manner, the jLabel pops up and flickers almost everywhere within its container. 我不希望这段简单的代码能奏效,但问题是它的行为不稳定,jLabel弹出并在容器内的几乎所有位置闪烁。

If it's of any help, layout is set to absolute. 如果有帮助,可以将布局设置为绝对。

Thanks. 谢谢。

As MadProgrammer pointed out, that was the issue. 正如MadProgrammer指出的那样,这就是问题所在。 This is my mouse drag method: 这是我的鼠标拖动方法:

private void jLabel2MouseDragged(java.awt.event.MouseEvent evt)  {                                     

  Point p = SwingUtilities.convertPoint(evt.getComponent(), evt.getPoint(), getContentPane());
  int x=p.x;
  int y=p.y;

  jLabel2.setLocation(x-120, y-120);
  jLabel2.repaint();

}   

The jLabel now moves smoothly. 现在,jLabel可以平稳移动。

My label is roughly 240x240 pixels, so I corrected the coordinates to have the center of the label placed where the mouse pointer is. 我的标签大约为240x240像素,因此我将坐标更正为将标签的中心放置在鼠标指针所在的位置。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM