0

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);
}
tibuurcio
  • 736
  • 8
  • 11
  • 1
    Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Nov 16 '14 at 05:14
  • And why on Earth are you offering a draggable button to the user? Is this app. a GUI designer? – Andrew Thompson Nov 16 '14 at 05:15
  • The button in this case is just as an example, if I change to some other JComponent it should work? Thanks for the link above, I'll take a look at it.. – tibuurcio Nov 16 '14 at 05:16
  • *"I'm getting strange positions."* Note the co-ordinates will be reported relative to whatever component the listener is attached to. – Andrew Thompson Nov 16 '14 at 05:16
  • *"The button in this case is just as an example.."* An example of how to stuff up a GUI? *"..if I change to some other JComponent it should work?"* No, it will fail just as completely. – Andrew Thompson Nov 16 '14 at 05:17
  • The goal here is just to be able to move a component through dragging the mouse. – tibuurcio Nov 16 '14 at 05:20
  • The 'goal' was obvious, I'm asking what the ***point*** of moving a component is? Explain it to me like it were a 'must have' feature listed on the box it is sold in. – Andrew Thompson Nov 16 '14 at 05:23
  • Ok, the point of moving is that after being able to move a component, I'll then try to link two components by a line, and when moving the components, the line should follow, like an extremely-simple UML system. – tibuurcio Nov 16 '14 at 05:27

0 Answers0