仅当在 Java 中按下鼠标时如何让 mouseEntered 执行
Posted
技术标签:
【中文标题】仅当在 Java 中按下鼠标时如何让 mouseEntered 执行【英文标题】:How to have mouseEntered execute only if mouse is pressed down in Java 【发布时间】:2012-05-21 02:41:38 【问题描述】:我只想在当前按下鼠标时执行 mouseEntered,基本上是这样的:
@Override
public void mouseEntered(MouseEvent e)
if(e.mouseDown())
//Do stuff
我可以这样做吗,或者我需要鼠标运动监听器还是什么?
谢谢!
编辑:抱歉应该更清楚地说明这一点,但我需要在它进入组件之前按下鼠标,就像按住鼠标并将鼠标悬停在组件上会激活监听器
【问题讨论】:
【参考方案1】:您可能想评估 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();
);
【讨论】:
@HovercraftFullOfEels 非常关注修饰符 +1以上是关于仅当在 Java 中按下鼠标时如何让 mouseEntered 执行的主要内容,如果未能解决你的问题,请参考以下文章