我想执行鼠标只有在当前按下鼠标时才输入,基本上是这样的:
@Override
public void mouseEntered(MouseEvent e) {
if(e.mouseDown()){
//Do stuff
}
}
我可以这样做吗,还是需要鼠标运动侦听器还是什么?
谢谢!
编辑:抱歉应该更清楚地说明这一点,但是我需要按下鼠标 在它进入组件之前,就像按住鼠标并将鼠标悬停在组件上会激活侦听器
您可能希望评估 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();
}
});
}
}