JLabel在尝试拖动时消失了

时间:2014-01-19 13:28:42

标签: java swing draggable jlabel drag

我正在构建一个应用程序,它将标签放在用户点击面板(jpanel2)的位置,并允许它移动放置的标签。

我可以成功放置标签,但我无法移动任何标签。事实上,当我尝试拖动标签时,它会在我的所有尝试中消失。 我也尝试在jPanel2和JFrame中调用重绘,但仍然没有成功。

JPanel 2没有布局(免费设计),因为想要将标签准确放置在鼠标点击的位置。

更新

以下是发生问题的最小示例。 我无法减少面板数量,因为我需要在屏幕上放置更多控件(例如jtable,菜单和工具栏)。

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                   
    }

2 个答案:

答案 0 :(得分:3)

如果您要使用GUI Builder制作程序,您需要做的是将面板的布局设置为null。然后,当您向面板添加标签时,需要为它们设置边界。下面是一个如何实现这一目标的例子。

  • 首先,我在框架表格(jPanel1)中添加了空白JPanel。我把它扩展到了框架的大小。
  • 然后我在构造函数中添加了所有其余的代码。我在JLabel然后jPanelrevalidate() repaint()添加了jPanel1
  • 然后我添加了MouseMotionListener

这是我添加的唯一代码。全部在构造函数中。除了pXpY变量作为类成员

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


这是完整的程序

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                   
}

答案 1 :(得分:0)

我改变了你的代码。
jpanel2顶部有一个面板(你用来添加jlabels的面板)。
我在initComponents()之后清除了jpanel2 jpanel2.removeAll();
它有效。


    /*
    * 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                   
    }