3

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

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

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

谢谢!

编辑:对不起应该更清楚,但我需要按下鼠标在它进入组件之前,它就像按住鼠标并将鼠标悬停在组件上会激活监听器

4

1 回答 1

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();
         }
      });
   }
}
于 2012-05-13T04:47:30.917 回答