gpt4 book ai didi

Java MouseListener 在按下鼠标时禁用 MouseMotionListener

转载 作者:行者123 更新时间:2023-12-01 20:08:54 25 4
gpt4 key购买 nike

构造函数内部:

   addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e){
//Do something
}
public void mouseReleased(MouseEvent e){
//Do something
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent evt) {
cursorX = evt.getX();
cursorY = evt.getY();
}
});

mouseMoved 正在运行,而我没有单击/按任何鼠标按钮。

但是当我单击或按住鼠标按钮时,光标位置不再更新,并且 mouseMoved 不会被调用

我花了几个小时寻找解决方案,请帮助我!

我尝试在类中实现 MouseListener 和 MouseMotionListener,但这也不起作用。

最佳答案

简单的答案是,按住按钮和不按住按钮时,鼠标在组件表面上移动是有区别的。系统将识别这些差异并调用不同的功能。

这是设计使然,大概是为了更容易管理这两个场景,这两个场景可以生成不同的结果(即拖放)

下面的例子是一个简单的演示。当按下鼠标按钮并移动鼠标时,mouseDragged将被调用,否则mouseMoved将被调用

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Released");
}
});

addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("Moved");
}

@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
}
});
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

}

}

关于Java MouseListener 在按下鼠标时禁用 MouseMotionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com