![](/img/trans.png)
[英]How to implement an image like a cue stick that rotates around a point as you drag your mouse with JavaFX
[英]how to drag an image around starting from the mouse position , in Java?
所以我是一個新的Java程序員,我正在嘗試學習如何使用JLabel處理GUI和移動圖像。
public class MyJava extends JFrame implements MouseListener, MouseMotionListener {
JLabel aJLabel;
public MyJava() {
this.setLayout(null);
aJLabel = new JLabel();
ImageIcon aImageIcon = new ImageIcon(this.getClass().getResource("avatar.jpg"));
aJLabel.setIcon(aImageIcon);
aJLabel.setBounds(50, 50, 200, 150);
this.getContentPane().add(aJLabel);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.setTitle("Title");
this.setSize(700, 600);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyJava();
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked, X=" + e.getX() + " ,Y=" + e.getY() + " ,Count=" + e.getClickCount());
}
@Override
public void mouseDragged(MouseEvent e) {
aJLabel.setBounds(e.getX()-120, e.getY()-120, 200, 150);
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("mouseMoved");
}}
我正在嘗試學習如何:
1-開始從我單擊的鼠標位置拖動?
僅在鼠標不在圖像邊界上的所有JLabel上拖動2了嗎?
僅當鼠標不在圖像邊界上才在所有JLabel上拖動嗎?
將偵聽器添加到標簽,而不是框架。
開始從我單擊的鼠標位置拖動?
確定單擊標簽的起點,並計算每個事件的鼠標位置變化。 基本代碼是:
public class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
使用此類的代碼為:
DragListener drag = new DragListener();
label.addMouseListener( drag );
label.addMouseMotionListener( drag );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.