I'm just learning java and I have a project where I want to be able to move a JLabel around a window with my mouse.
I set up a class called BasicWindow1, implemented a MouseMotionListener, instantiated a JFrame container, added a JLabel to the JFrame, set up a mouseDragged method, hooked up the setBounds method of the JLabel to the MouseEvent information, compiled it and it ran ...
BUT ......
when I dragged the JLabel a second GHOST label appeared above it and moved happily along with its virtual brother.
I've included the code below and I'm hoping someone will take an interest and straighten me out. I'm guessing it's probably a simple beginner's mistake, but it's driving me crazy.
On the debugging level, I inserted a println(e) with the MouseEvent in the mouseDragged method and it showed that the MOUSE_DRAGGED x,y elements were oscillating between 2 distinct x,y paths, one for the GHOST and one for its virtual brother.
Thanks for looking, Mike
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BasicWindow1 implements MouseMotionListener {
JFrame jf = new JFrame();
JLabel label2 = new JLabel("label2");
public BasicWindow1(String string) {
//JFrame
jf.setTitle(string);
jf.setSize(400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.setVisible(true);
label2.setOpaque(true);
label2.setBackground(Color.cyan);
label2.setBounds(0,150,75,25);
label2.addMouseMotionListener(this);
jf.add(label2);
}//end constructor
public void mouseDragged(MouseEvent e) {
label2.setBounds(e.getX(),e.getY(),75,25);
System.out.println("e = " + e);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
BasicWindow1 mybw = new BasicWindow1("Basic Window for Stack Overflow");
}
}