Miguel Ribeiro
Miguel Ribeiro

Reputation: 8184

JLabel disappears when trying to drag it

I'm building an application that puts labels where the user clicks on a panel (jpanel2) and also allow it to move the placed labels.

I can successfully place the labels but I'm not being able to move any of them. In fact, when I try to drag a label it just disappears, in all my tries. I also tried to invoke the repaint in jPanel2 and JFrame but still no success.

JPanel 2 has no Layout (free design) as want to place the labels exactly where the mouse clicked.

UPDATE

Here is a minimal example of the problem happening. I cannot reduce the number of panels as I'll need to put more controls on the screen (such as a jtable, menu and toolbar).

public class Example extends javax.swing.JFrame {

    static int count = 0;

    public Example() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                 
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(600, 600));

        jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel2MouseClicked(evt);
            }
        });

        jPanel3.setMinimumSize(new java.awt.Dimension(0, 0));
        jPanel3.setLayout(new java.awt.BorderLayout());
        jPanel3.add(jLabel1, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>                        

    private void jPanel2MouseClicked(java.awt.event.MouseEvent evt) {                                     

        count++;
        addAnnotation(String.valueOf(count), evt.getX(), evt.getY());
    }                                    

    private void addAnnotation(String labelStr, int x, int y) {

        final JLabel label = new JLabel(labelStr);
        jPanel2.add(label);
        label.setLocation(x, y);

        System.out.println("Adding to " + x + " " + y);

        label.setSize(20, 20);
        label.setBackground(Color.WHITE);
        label.setOpaque(true);
        label.setBorder(new LineBorder(Color.BLACK, 1, false));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVisible(true);
        label.setForeground(Color.BLACK);

        label.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent e) {
                Component c = e.getComponent();

                int moveToX = c.getX() + e.getX();
                int moveToY = c.getY() + e.getY();
                c.setLocation(moveToX, moveToY);
                System.out.println("Moving to " + moveToX + " " + moveToY);
            }

            @Override
            public void mouseMoved(MouseEvent e) {
            }
        });
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Example().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration                   
    }

Upvotes: 2

Views: 819

Answers (2)

chathux
chathux

Reputation: 831

i changed your code a little bit.
there was a panel on the top of jpanel2( the panel you are using to add jlabels).
i cleared jpanel2 just after the initComponents() by jpanel2.removeAll();
and it worked.


    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package javaapplication16;

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import javax.swing.SwingUtilities;
    import javax.swing.border.LineBorder;

    public class E extends javax.swing.JFrame {

        static int count = 0;

        public E() {
            initComponents();


            //jPanel2.setBackground(Color.YELLOW);;
            jPanel2.removeAll();;


        }

        @SuppressWarnings("unchecked")                 
        private void initComponents() {

            jPanel1 = new javax.swing.JPanel();
            jPanel2 = new javax.swing.JPanel();
            jPanel3 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setPreferredSize(new java.awt.Dimension(600, 600));

            jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jPanel2MouseClicked(evt);
                }
            });

            jPanel3.setMinimumSize(new java.awt.Dimension(0, 0));
            jPanel3.setLayout(new java.awt.BorderLayout());
            jPanel3.add(jLabel1, java.awt.BorderLayout.CENTER);

            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );

            getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

            pack();
        }//                         

        private void jPanel2MouseClicked(java.awt.event.MouseEvent evt) {                                     

            count++;
            addAnnotation(String.valueOf(count), evt.getX(), evt.getY());
        }                                    

        private void addAnnotation(String labelStr, int x, int y) {

            final JLabel label = new JLabel(labelStr);
            jPanel2.add(label);
            label.setLocation(x, y);

            System.out.println("Adding to " + x + " " + y);

            label.setSize(200, 200);
            label.setBackground(Color.WHITE);
            label.setOpaque(true);
            label.setBorder(new LineBorder(Color.BLACK, 1, false));
            label.setHorizontalAlignment(SwingConstants.CENTER);
            label.setVisible(true);
            label.setForeground(Color.BLACK);



            label.addMouseMotionListener(new MouseMotionListener() {


                @Override
                public void mouseDragged(MouseEvent e) {
                    Component c = e.getComponent();


                    int moveToX = e.getX() + c.getX();
                    int moveToY = e.getY() + c.getY();

                    c.setLocation(moveToX, moveToY);
                    c.repaint();

                }

                @Override
                public void mouseMoved(MouseEvent e) {

                    //Component c = e.getComponent();


                }
            });


        }

        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
            * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
            */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(E.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(E.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(E.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(E.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new E().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                     
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
    // End of variables declaration                   
    }

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208944

If you're going to make the program, using GUI Builder, what you need to do is set the panel's layout to null. Then when you add a label to the panel, you need to set bounds to them. below is an example of how you can accomplish this.

  • First I added a blank JPanel to the frame form (jPanel1). I extended it to the size of the frame.
  • Then I added all the rest of the code in the constructor. I added a JLabel to the jPanel then revalidate() and repaint() the jPanel1.
  • Then I added the MouseMotionListener

Here is the only code I added. All in the constructor. Except a pX and pY variable as class members

int pX, pY;
public NewJFrame() {
    initComponents();
    jPanel1.setLayout(null);
    final JLabel label = new JLabel();
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setBounds(50, 50, 50, 50);
    label.setBorder(new LineBorder(Color.black, 3));
    label.setText("Hello");

    label.addMouseMotionListener(new MouseMotionAdapter(){
        public void mouseDragged(MouseEvent me) {
            label.setLocation(label.getLocation().x + me.getX() - pX, 
                        label.getLocation().y + me.getY() - pY);
            jPanel1.revalidate();
            jPanel1.repaint();
        }
    });
    label.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent me) {
                // Get x,y and store them
                pX = me.getX();
                pY = me.getY();
            }
        });

    jPanel1.add(label);
    jPanel1.revalidate();
    jPanel1.repaint();
}

enter image description here


Here's the complete program

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

public class NewJFrame extends javax.swing.JFrame {

    int pX, pY;
    public NewJFrame() {
        initComponents();
        jPanel1.setLayout(null);
        final JLabel label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setBounds(50, 50, 50, 50);
        label.setBorder(new LineBorder(Color.black, 3));
        label.setText("Hello");

        label.addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseDragged(MouseEvent me) {
                label.setLocation(label.getLocation().x + me.getX() - pX, 
                            label.getLocation().y + me.getY() - pY);
                jPanel1.revalidate();
                jPanel1.repaint();
            }
        });
        label.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent me) {
                    // Get x,y and store them
                    pX = me.getX();
                    pY = me.getY();
                }
            });

        jPanel1.add(label);
        jPanel1.revalidate();
        jPanel1.repaint();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 388, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 288, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

Upvotes: 3

Related Questions