This discussion is archived
2 Replies Latest reply: Jan 6, 2005 9:45 AM by 807596 RSS

To drag a button

807596 Newbie
Currently Being Moderated
I'm trying to write an applet with a frame and a button in it.

But I can't drag correctly the button because when I click on it, it trembles and become two buttons!!!

The following code is simple:

import java.awt.Graphics;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;

public class DragButton extends Applet
{
     Frame F = new Frame("DragButton window");
Button B1 = new Button("click here");
     int X;
     int Y;
     public void init()
     {
          F.setSize(400,200);
F.setLocation(100,100);
F.add(B1);
          B1.setBounds(100,100,80,40);
          MouseListenerClass M1 = new MouseListenerClass();
          B1.addMouseMotionListener(M1);
F.setVisible(true);
     }

     private class MouseListenerClass extends MouseMotionAdapter
     {
          public void mouseMoved(MouseEvent E)
          {
               X=E.getX();
               Y=E.getY();
               B1.setBounds(X,Y,80,40);
          }
     }
}
It compiles successfully.

I'm new at java, please tell me where I'm in trouble with the style

Thanks in advance!
Max
  • 1. Re: To drag a button
    807596 Newbie
    Currently Being Moderated
    Sorry the correct code is:


    import java.awt.Graphics;
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;

    public class DragButton extends Applet
    {
    Frame F = new Frame("DragButton window");
    Button B1 = new Button("click here");
    int X;
    int Y;
    public void init()
    {
    F.setSize(400,200);
    F.setLocation(100,100);
    F.add(B1);
    B1.setBounds(100,100,80,40);
    MouseListenerClass M1 = new MouseListenerClass();
    B1.addMouseMotionListener(M1);
    F.setVisible(true);
    }

    private class MouseListenerClass extends MouseMotionAdapter
    {
    public void mouseDragged(MouseEvent E)
    {
    X=E.getX();
    Y=E.getY();
    B1.setBounds(X,Y,80,40);
    }
    }
    }

    With "mouseMoved" method it works fine.
  • 2. Re: To drag a button
    807596 Newbie
    Currently Being Moderated
    Sorry
    the real code is with "mouseDragged" in place of "mouseMoved".