3

I Want to execute the mouseEntered only IF the mouse is currently pressed down, basically this:

    @Override
    public void mouseEntered(MouseEvent e) {
       if(e.mouseDown()){
         //Do stuff
        }
    }

can I do it like this, or do I need a mouse motion listener or what?

Thanks!

EDIT: Sorry should have made this more clear, but I need the mouse to be press down Before it enters the component, its like holding down the mouse and hovering over the component activates the listener

1 Answer 1

7

You might want to evaluate the MouseEvent API to see what methods are available, as I think that you will find your solution there:

  myComponent.addMouseListener(new MouseAdapter() {

     @Override
     public void mouseEntered(MouseEvent mEvt) {
        System.out.println("mouse entered");

        if (mEvt.getModifiers() == MouseEvent.BUTTON1_MASK) {
           System.out.println("Mouse dragging as entered");
        }

     }

  });

For example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEnteredPressed extends JPanel {
   private static final int SIDE = 500;

   public MouseEnteredPressed() {
      setLayout(new GridBagLayout());
      JLabel label = new JLabel("Hovercraft Rules The World!");
      label.setFont(label.getFont().deriveFont(Font.BOLD, 24));
      label.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
      add(label);

      label.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseEntered(MouseEvent mEvt) {
            System.out.println("mouse entered");

            if (mEvt.getModifiers() == MouseEvent.BUTTON1_MASK) {
               System.out.println("Mouse dragging as entered");
            }
         }
      });

   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(SIDE, SIDE);
   }

   private static void createAndShowGui() {
      MouseEnteredPressed mainPanel = new MouseEnteredPressed();

      JFrame frame = new JFrame("MouseEnteredPressed");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@HovercraftFullOfEels great eye on modifiers +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.