Move button

Posted on 2005-05-16
Last Modified: 2011-10-03
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 ?
Question by:hahahahahaha
    LVL 86

    Accepted Solution

    You need to implement a null layout and set the bounds of the button in the dragged event
    LVL 92

    Assisted Solution

    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);

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
    Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
    Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
    This video teaches viewers about errors in exception handling.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now