Move button

Here is my applet

import java.awt.event.*;

import javax.swing.*;

public class Diagram extends JApplet {
      private JButton b;
      private Box box;

      public void init()
      {
            box = Box.createVerticalBox();
            b = new JButton("Hello");
            box.add(b);
            getContentPane().add(box);
            MyMoveListener moveListener = new MyMoveListener();
            b.addMouseMotionListener( moveListener );
      }

      private class MyMoveListener extends MouseMotionAdapter {
                  public void mouseDragged(MouseEvent e)
                  {
                        
                  }
      }
}


When they press and move mouse , I want that button is moved too . How can I do ?
hahahahahahaAsked:
Who is Participating?
 
CEHJCommented:
You need to implement a null layout and set the bounds of the button in the dragged event
0
 
objectsCommented:
Add your mouse listener to the box and not the button, and set the buttons location using the following:

               public void mouseDragged(MouseEvent e)
               {
                     b.setLocation(e.getX(), e.getY());
               }

No point using a Box though, you may as well replace it with a JPanel

private JPanel box = new JPanel(null);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.