简体   繁体   中英

How to have mouseEntered execute only if mouse is pressed down in Java

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

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();
         }
      });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM