当我拖动鼠标时,对象从不同的位置开始,
我想要开始鼠标位置和对象位置相同的位置 开始。
我试过一些方法,无法在谷歌找到解决方案。 所以我提出了问题。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();
}
}
答案 0 :(得分:3)
您需要从按钮的新X和Y位置减去单击按钮的位置。您可以通过向按钮添加MouseListener
mousePressed
方法来获取这些内容。我认为如果你创建一个从MouseAdapter
扩展的新类来组合这两种方法会更容易。
public movingButton() {
[...]
MouseAdapter myMouseAdapter = new MouseAdapter(){
int mouseClickedPosX = 0;
int mouseClickedPosY = 0;
@Override
public void mousePressed(MouseEvent E){
mouseClickedPosX = E.getX();
mouseClickedPosY = E.getY();
}
@Override
public void mouseDragged(MouseEvent E){
int X = E.getX() + button.getX() - mouseClickedPosX;
int Y = E.getY() + button.getY() - mouseClickedPosY;
button.setBounds(X, Y,150,40);
}
};
button.addMouseListener(myMouseAdapter);
button.addMouseMotionListener(myMouseAdapter);
}