问题描述
我需要实现一个类,使用Swing,当用户点击屏幕上的任何地方时,它可以获取鼠标坐标.如果我想在我自己的窗口内获取鼠标坐标,我会使用 MouseListener
,但我希望它即使在用户在我的程序外单击时也能工作.
I need to implement a class, using Swing, which can obtain the mouse coordinates when the user clicks anywhere on the screen. if I wanted to obtain the mouse coordinates inside my own window, I'd use a MouseListener
, but I want it to work even when the user clicks outside my program.
我希望我的类表现得像 KColorChooser:用户点击下拉菜单按钮,他可以点击屏幕上的任意位置来获取该点的颜色.但我不知道使用纯 Java 是否可行.
I want my class to behave just like KColorChooser: the user clicks on the drop button and he can click anywhere on the screen to obtain the color of that spot. but I don't know if that's possible using pure Java.
推荐答案
有可能,但有限:
为焦点事件添加 AWTEventListener.只要您的应用程序在按钮被点击之前获得焦点,您就会收到一个焦点丢失事件.然后查询指针位置.
Add an AWTEventListener for focus events. As long as your app has focus before the button is clicked you'll receive a focus lost event. Then query for the pointer position.
当然,限制在于您的应用会失去焦点.因此,根据您最终要实现的目标,这可能没有用.
The limitation is that, of course, your app loses focus. So depending on what you are ultimately trying to achieve this might not be useful.
如果您不想失去焦点,那么您将不得不临时截取整个屏幕的屏幕截图并将其显示在屏幕填充窗口中,该窗口会像往常一样监听鼠标点击.
If you don't want to lose focus then you will have to temporarily take a screenshot of the whole screen and display that in a screen filling window which listens for a mouse click as usual.
第一种方法的证明:
import java.awt.AWTEvent;
import java.awt.MouseInfo;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import javax.swing.JFrame;
public class Application1 {
public static void main(String[] args) {
Toolkit.getDefaultToolkit().addAWTEventListener(
new Listener(), AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static class Listener implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
System.out.print(MouseInfo.getPointerInfo().getLocation() + " | ");
System.out.println(event);
}
}
}
在生成的应用之外点击:
Clicking outside of the app produced:
java.awt.Point[x=198,y=59] | java.awt.event.MouseEvent[MOUSE_EXITED, ...
java.awt.Point[x=976,y=503] | java.awt.FocusEvent[FOCUS_LOST, ...
第二点在应用之外.
这篇关于如何在我的窗口外在 Java 中获取鼠标点击坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!