Problem with dragging a JButton on frame

the problem is that is see kinds of bugs when i drag it like i see two buttons and when i release it i see one button again

mport java.awt.*;

import java.awt.event.*;

import javax.swing.*;

publicclass MainFrameextends JFrame{

int x=0;

ImageIcon img1=new ImageIcon("circle.JPG");

JButton enterButton=new JButton(img1);

public MainFrame(){

super("topic");

this.getContentPane().setLayout(null);

setLocation(120,70);

enterButton.setBorder(null);

enterButton.setRequestFocusEnabled(false);

enterButton.setFocusable(false);

enterButton.setFont(new Font("David",Font.BOLD,18));

enterButton.setSize(98,97);

enterButton.setLocation(302,342);

enterButton.addMouseMotionListener(new MyMouseListener());

this.getContentPane().add(enterButton);

setResizable(false);

setSize(800,600);

setVisible(true);

this.addWindowListener(new MyWindowListener());

this.setDefaultCloseOperation(0);

}

publicvoid exit(){

int returnAns=JOptionPane.showConfirmDialog(null,"are you sure you want exit?","exit",JOptionPane.ERROR_MESSAGE);

if (returnAns==JOptionPane.YES_OPTION){

System.exit(0);

}

}

privateclass MyMouseListenerimplements MouseMotionListener{

publicvoid mouseDragged(MouseEvent e){

//System.out.println("mouseDragged");

System.out.print("x "+e.getX());

System.out.print("y "+e.getY());

enterButton.setLocation(e.getX(),e.getY());

repaint();

}

publicvoid mouseMoved(MouseEvent e){

}

}

publicclass MyWindowListenerextends WindowAdapter{

publicvoid windowClosing(WindowEvent e){

exit();

}

}

}

[3659 byte] By [deviancea] at [2007-10-3 10:21:25]
# 1

add this class field

Point startPt;

add this mouse listener to the constructor

enterButton.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent me){

startPt = me.getPoint();

}

});

the new mouseDragged

public void mouseDragged(MouseEvent e) {

enterButton.setLocation(enterButton.getX()+e.getX()-startPt.x,

enterButton.getY()+e.getY()-startPt.y);

}

try to understand the code in mouseDragged

Michael_Dunna at 2007-7-15 5:42:55 > top of Java-index,Desktop,Core GUI APIs...