gpt4 book ai didi

java - 如何让我的 JWindow 窗口始终保持焦点

转载 作者:行者123 更新时间:2023-12-02 06:43:29 24 4
gpt4 key购买 nike

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

最佳答案

您的问题对于为什么要在鼠标离开 JWindow 后继续处理鼠标有点含糊...但是

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

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

enter image description here

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如果支持平台,有助于将窗口保持在其他窗口之上

关于java - 如何让我的 JWindow 窗口始终保持焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885247/

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