简体   繁体   English

Java JDialog交互而无需关注macOS

[英]Java JDialog interaction without taking focus on macOS

i know there is a lot of discussions around this question but this is different. 我知道围绕这个问题有很多讨论,但这是不同的。 We have a java application that show a JDialog on a Keyboard event on Windows (Native hook). 我们有一个Java应用程序,该应用程序在Windows的Keyboard事件上显示JDialog(本机挂钩)。 It works fine, when i click something in the java window, the focus of the current application is not lost. 它工作正常,当我在Java窗口中单击某些内容时,当前应用程序的焦点不会丢失。 On macOS, it change the active application to my java window. 在macOS上,它将活动应用程序更改为我的Java窗口。 I managed to hide the dock icon with this : 我设法用这个隐藏了停靠图标:

-Dglass.taskbarApplication=false

But this is not enough, i want my java application to never be focused. 但这还不够,我希望我的Java应用程序永远不会受到关注。 I read about the headless property and it cannot work since i show a JDialog. 我读到有关headless属性的信息,由于我显示了JDialog,因此它无法工作。 It works perfectly in Windows but on Mac, a tray application is not the same i guess. 它在Windows中完美运行,但是在Mac上,我猜它是一个托盘应用程序。 Is this possible? 这可能吗? Is the problem with the JDialog or can i add some argument to run my java application in the background? 是JDialog的问题,还是我可以添加一些参数以在后台运行Java应用程序? Thanks 谢谢

Note: The solution below is tested on OS X only 注意:以下解决方案仅在OS X上经过测试

Forcing the JDialog to have a type of Window.Type#POPUP as shown below seems to work. 强制JDialog具有Window.Type#POPUP类型,如下所示。

dialog.setType(Window.Type.POPUP);

This allows the dialog to be focusable and when it gains focus other windows won't lose focus, like a popup menu. 这样可以使对话框具有焦点,并且当它获得焦点时,其他窗口也不会失去焦点,例如弹出菜单。 However, it also has other effects like making the dialog behave as if dialog.setAlwaysOnTop(true) has been called. 但是,它还具有其他效果,例如使对话框表现得好像已调用dialog.setAlwaysOnTop(true)

Note: The example application below unfocuses other windows on startup but not after the unfocused windows are focused again. 注意:下面的示例应用程序在启动时将其他窗口置于非焦点状态,但在未聚焦的窗口再次被聚焦之后则不会。

Example: 例:

import java.awt.EventQueue;
import java.awt.Window;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class NonUnfocusingDialogExample {

    public static void main(final String[] args) {
        EventQueue.invokeLater(() -> {
            final JDialog dialog = new JDialog();
            dialog.setType(Window.Type.POPUP);
            dialog.getContentPane().add(new JLabel("Hello World!", 
                    SwingConstants.CENTER));
            dialog.pack();
            dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            dialog.setTitle("Test Dialog");
            dialog.setLocationByPlatform(true);
            dialog.setVisible(true);
        });
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM