0

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

4

1 回答 1

2

你的问题有点模糊,为什么你想在鼠标离开后继续处理JWindow......但是

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

下面演示了后者,使用MouseInfoand ajavax.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如果支持该平台,您还可以找到帮助将窗口保持在其他窗口之上

于 2013-09-19T02:29:55.117 回答