javaswingjframemousemotionlistener

Jlabel not moving with mouse motion listener


I'm trying to implement a JLabel which moves with mouse pointer in a container with mouseMotionListener, but the JLabel does not appear on the screen. Any suggestions?

public class Ships extends JFrame implements ActionListener{

    private JPanel contentPane;

    int x=418,p=75,l=10;


    public static void main(String[] args) {
        Ships m = new Ships();

    }

    JLabel lblNewLabel = new JLabel();

    JLabel l5 = new JLabel();

    Container container;
    /**
    * Create the frame.
    */
    public Ships() {
         Container container= getContentPane();


        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 1363, 730);
        contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(null);
        setVisible(true);

        l5.setIcon(new ImageIcon("C:\\Users\\The Wimpster\\Desktop\\images22.png"));
        container.add(l5);
        l5.setBounds(0, 10, 75, 50);//this label is supposed to move with mouse pointer
        container.addMouseMotionListener(new MouseAdapter(){ 
            public void mouseMoved(MouseEvent e){
                p = e.getX();
                l = e.getY();
                l5.setBounds(p,l,150,50); 
            }
        });
    }
}

Solution

  • You are creating two instances of your Ships class - which the constructor calls setVisible(true) so two instances appear - this is probably not desired.

    However the problem really comes about because you are getting the content pane of the form, then creating a new panel, setting that as the new content pane then you add the label to the old pane, then add the mouse listener to the old content pane.

    Just remove the references to the existing pane and it'll work.

    public Ships() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 1363, 730);
        contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(null);
        setVisible(true);
    
        l5.setIcon(new ImageIcon("C:\\Users\\The Wimpster\\Desktop\\images22.png"));
        // 
        contentPane .add(l5);
        l5.setBounds(0, 10, 75, 50);//this label is supposed to move with mouse pointer
        contentPane .addMouseMotionListener(new MouseAdapter(){ 
            public void mouseMoved(MouseEvent e){
                p = e.getX();
                l = e.getY();
                l5.setBounds(p,l,150,50); 
            }
        }); 
    }