I have a simple Java code where I attach a MouseMotionListener to a JButton and refresh the button's position everytime the mouse is dragged, however, I'm getting strange positions. Is there a better way to do it? I've been unlucky to find any solutions.
public static void main(String[] args) {
JFrame frame = new JFrame("Janela 1");
JPanel myPainel = new JPanel();
myPainel.setLayout(null);
final JButton btn = new JButton("First button");
btn.setBounds(0,0,100,50);
//btn.setLocation(50, 50);
btn.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
btn.setBounds((int)p.getX(), (int)p.getY(), 100, 50);
}
@Override
public void mouseMoved(MouseEvent e) {
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(myPainel);
myPainel.add(btn);
frame.setSize(600, 400);
frame.setVisible(true);
}
EDIT: I'm able to improve the moviment with this code:
public void mouseDragged(MouseEvent e) {
Point p = MouseInfo.getPointerInfo().getLocation();
btn.setBounds((int)p.getX() - 50, (int)p.getY() - 50, 100, 50);
}