Search code examples
javaswingdrag-and-dropjlabel

Moving a JLabel Around JPanel


I have a JPanel that has 2+ JLables on it, I would like to be able to grab a label then move it to a different location on the JPanel. How can I do that? The only things I can find on this are moving a label from component "A" to component "B", nothing about moving it around on a Panel.


Solution

  • Here is what I wanted:

    public class LayerItem extends JLabel{
    
        protected int lblYPt = 0;
    
        public LayerItem(JPanel layers){
            this.addMouseListener(new MouseAdapter(){
                @Override
                 public void mousePressed(MouseEvent evt){
                     lblMousePressed(evt);
                 }
            });
    
            this.addMouseMotionListener(new MouseAdapter(){
                @Override
                public void mouseDragged(MouseEvent evt){
                    lblMouseDragged(evt);
                }
            });
        }
    
        public void lblMousePressed(MouseEvent evt){
            lblYPt = evt.getY();
        }
    
        public void lblMouseDragged(MouseEvent evt){
            Component parent = evt.getComponent().getParent();
            Point mouse = parent.getMousePosition();
            try{
                if(mouse.y - lblYPt >= 30){
                    this.setBounds(0, mouse.y - lblYPt, 198, 50);
                }
            }catch(Exception e){
            }
        }
    }