如何让我的JWindow窗口始终保持专注

我正在制作一个包含JWindow的java应用程序。 我希望能够跟踪鼠标而无需用户在转到另一个窗口后点击窗口。

你的问题对于你为什么要在离开JWindow继续处理鼠标有点模糊……但是

当您在应用程序外部使用鼠标时,您有两个(基本)选择,您可以使用JNI / JNA解决方案,也可以轮询MouseInfo

下面演示了后者,使用MouseInfojavax.swing.Timer来更新标签……

在此处输入图像描述

 import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.MouseInfo; import java.awt.PointerInfo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class MouseWindow { public static void main(String[] args) { new MouseWindow(); } public MouseWindow() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private JLabel label; public TestPane() { setLayout(new BorderLayout()); label = new JLabel(); label.setFont(label.getFont().deriveFont(48f)); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); add(label); updateMouseInfo(); Timer timer = new Timer(250, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateMouseInfo(); } }); timer.start(); } protected void updateMouseInfo() { PointerInfo pi = MouseInfo.getPointerInfo(); label.setText(pi.getLocation().x + "x" + pi.getLocation().y); } } } 

更新

如果支持平台,您还可以找到Window#setAlwaysOnTop的帮助,以保持窗口在其他人的Window#setAlwaysOnTop