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");
            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 ?
Who is Participating?
You need to implement a null layout and set the bounds of the button in the dragged event
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);
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.