<分区>
当我拖动鼠标时,对象从不同的位置开始,
我想开始鼠标位置和对象中心位置具有相同的位置 开始。
我尝试了一些方法,但无法在谷歌中找到解决方案。 所以我提出了问题。
package math;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class movingButton extends JFrame {
private JButton button;
public movingButton() {
super("Position helper");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setSize(500, 520);
super.setVisible(true);
super.setLayout(null);
button = new JButton("drag me ");
add(button);
button.setBounds(100, 100, 150, 40);
button.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent E) {
int X = E.getX() + button.getX();
int Y = E.getY() + button.getY();
button.setBounds(X, Y, 150, 40);
}
});
}
}
public class Main {
public static void main(String args[]) {
new movingButton();
}
}