Search code examples
javaswingmousemotionlistener

Does JLabel have default implementation of mouseMotionListener?


I want to ask if JLabel has default implementation of mouseMotionListener.

I use addAWTEventListener method to Toolkit.getDefaultToolkit() with MOUSE_MOTION_EVENT_MASK in order to runtime it will be able to know over which control the mouse is. Over jButton, jFrame, jTextfield everything work fine but over JLabel , JPanel and others do not.

If I add to JLabel the code above

lblNewLabel_1.addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
        }
    });

it works.

I have to add something similar to all controls which now haven't MouseMotionListener?


Solution

  •   public class something implements MouseMotionListener{    
    
          public something(){
            button.addMouseMotionListener(this);
            frame.addMouseMotionListener(this);
            panel.addMouseMotionListener(this);
            JTextField.addMouseMotionListener(this);          
          }   
    
    //MouseMotionListener methods
    
         @Override
         public void mouseDragged(MouseEvent e) {    
            // TODO Auto-generated method stub          
        }
    
        @Override
        public void mouseMoved(MouseEvent e) {    
            // TODO Auto-generated method stub          
        }     
    }
    

    And yes you must add a mouseOrMotion Listener or action Listener if you expect an action from them

    And something more when you want to add a JLabel to window don't add it directly but first add the JLabel to a JPanel and then window.add(panel). Cause JLabel is lightweight component and JFrame heavyweight and may cause you a lot of problems with listeners.

    Let me know if that's not enough...