【问题标题】:Java Virtual Keyboard for Mac用于 Mac 的 Java 虚拟键盘
【发布时间】:2016-11-18 06:22:43
【问题描述】:

我正在开发适用于 Windows 和 macOS 的屏幕键盘,并且我制作了一个小测试应用程序。它有一个按钮,并在活动应用程序中键入字母“M”。它适用于 Windows 10,但不适用于 Mac(我正在运行 macOS 10.12)。在 macOS 中,只要我按下按钮,无论我尝试发送“M”的哪个应用程序都会失去焦点(文本输入的光标消失),即使我的单个按钮“键盘”已经 setFocusable(false)这个地方。我也在按钮上尝试了自己的 MouseListener。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class main {
    private static Robot robot;
    private static Rectangle rectangle;

    public static void main(String[] args){
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        Button button = new Button("M");
        button.setFocusable(false);

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(100, 100);
        frame.add(button);

        frame.setAlwaysOnTop(true);

        //set everything I can think of to unfocusable!!!
        frame.setFocusable(false);
        frame.setAutoRequestFocus(false);
        frame.setFocusableWindowState(false);
        frame.getRootPane().setFocusable(false);
        frame.setVisible(true);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendKeystroke();
            }
        });
        //Instead of adding a listener to the button, I've also tried my own MouseListener.
/*        button.addMouseListener(new MouseTrap());
        rectangle = button.getBounds();*/
    }

    private static void sendKeystroke(){
        robot.keyPress(KeyEvent.VK_M);
        robot.keyRelease(KeyEvent.VK_M);
    }

    private static class MouseTrap extends MouseAdapter{
        @Override
        public void mouseClicked(MouseEvent e) {
            if (rectangle.contains(e.getPoint())){
                sendKeystroke();
            }
        }
    }
}

似乎 macOS 确实让某些应用程序获得焦点,而不会从另一个应用程序中获取光标。例如从系统托盘中搜索 VMware 或 Spotlight。

Cursor for VMware and IntelliJ at the same time

我见过其他非 Java 的答案:

Virtual Keyboard Cocoa & Objective C

但是,当 Java 在 Windows 上运行时,我真的必须全部采用原生方式吗?除了学习曲线(没有在 Mac 上做任何本机操作)之外,我想保持 Win 和 Mac 版本尽可能接近。

任何人都知道我如何使用纯 Java 来完成这项工作吗?

(注意:与上述链接的提问者一样,我不能只使用键盘视图,因为我想从键盘发送修改/附加数据,例如文本预测。我相信这需要额外的本机代码再次。)

【问题讨论】:

    标签: java macos


    【解决方案1】:

    我非常努力地寻找方法。但似乎没有任何本机代码的纯Java是不可能的。

    【讨论】:

      猜你喜欢
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2015-01-02
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多