macos 如何在 Java 中创建覆盖窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1768062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:33:26  来源:igfitidea点击:

How to create an overlay window in Java?

javacocoaswingmacosoverlay

提问by Sami

I'm trying to create a HUD style display for a foreign application.

我正在尝试为外国应用程序创建 HUD 风格的显示。

To do this, I'd need to make a transparent overlay window, that would be placed on top of the window of the foreign application. The overlay window should allow me to place widgets and draw text on it. Events should get forwarded to the underlying window, if they happen on the transparent area (and otherwise allow the widgets to work as expected).

为此,我需要制作一个透明的覆盖窗口,该窗口将放置在外部应用程序窗口的顶部。覆盖窗口应该允许我放置小部件并在其上绘制文本。事件应该被转发到底层窗口,如果它们发生在透明区域(否则允许小部件按预期工作)。

I'm doing this on OSX with Java. I'd hope to do this with pure Java with portability to other platforms, but if not possible, I'd be fine with solutions that would just allow me to do this on OSX through Cocoa (Rococoa) or Carbon.

我在 OSX 上用 Java 做这个。我希望使用具有可移植性到其他平台的纯 Java 来做到这一点,但如果不可能,我会接受那些只允许我通过 Cocoa (Rococoa) 或 Carbon 在 OSX 上执行此操作的解决方案。

回答by Sami

Actually, was able to figure this out myself. Seems to be easier than I expected:

事实上,我自己也能弄清楚这一点。似乎比我预期的要容易:

public class Overlay {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Transparent Window");
        frame.setUndecorated(true);
        frame.setBackground(new Color(0, 0, 0, 0));
        frame.setAlwaysOnTop(true);
        // Without this, the window is draggable from any non transparent
        // point, including points  inside textboxes.
        frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", false);

        frame.getContentPane().setLayout(new java.awt.BorderLayout());
        frame.getContentPane().add(new JTextField("text field north"), java.awt.BorderLayout.NORTH);
        frame.getContentPane().add(new JTextField("text field south"), java.awt.BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.pack();
    }
}

回答by furkanayilmaz

If you want to create a window for your game or something else use the JFrame.

如果你想为你的游戏或其他东西创建一个窗口,请使用JFrame.