如何在Java中按下鼠标时执行mouseEntered

时间:2012-05-13 04:40:08

标签: java event-handling mouseevent listener

我只想在鼠标当前按下时执行mouseEntered,基本上就是这样:

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

我可以这样做吗,还是我需要鼠标运动监听器或什么?

谢谢!

编辑:抱歉应该让这个更清楚,但我需要按下鼠标才能进入组件之前,就像按住鼠标并将鼠标悬停在组件上一样可以激活监听器

1 个答案:

答案 0 :(得分:7)

您可能想要评估MouseEvent API以查看可用的方法,因为我认为您可以在那里找到解决方案:

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

     }

  });

例如:

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