且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JOptionPane显示在父JFrame的后面

更新时间:2023-11-22 16:34:52

您在Linux上看到的行为符合API规范.这就是窗口的说法.setAlwaysOnTop():

The behaviour you see on Linux is in accordance with the API specification. This is what it says for Window.setAlwaysOnTop():

如果存在多个始终位于最上层的窗口,则它们的相对顺序是不确定的,并且取决于平台.

If there are multiple always-on-top windows, their relative order is unspecified and platform dependent.

还有:

始终位于最上层的窗口拥有的所有窗口都继承此状态,并自动变为始终处于最上层.

All windows owned by an always-on-top window inherit this state and automatically become always-on-top.

这将解释为什么位于JOptionPane核心的JDialog也具有总是在最前面"的状态.似乎在Windows上它偶然会按预期运行,但实际上您是在要求Swing做一些不可能的事情:在总是在其他窗口上方"显示父级,并在其上方显示对话框.

Which would explain why the JDialog that's at the heart of JOptionPane also has "always on top" status. Seems that on Windows by chance it works as you expected, but really you're asking Swing to do something impossible: To show the parent "always above other windows", but also to show the dialog on top of it.

这是一种可能的解决方法:将对话框放置在父对话框旁边,以便当它在z轴上位于对话框下方时,用户仍会看到它:

Here's a possible workaround: Place the dialog next to the parent, so that while it's under it on the z-axis, the user will still see it:

JDialog dialog = new JOptionPane("Message").createDialog(parent, "Title");
Point dialogLoc = dialog.getLocation();
Point parentLoc = parent.getLocation();
dialog.setLocation(parentLoc.x + parent.getWidth(), dialogLoc.y);
dialog.setVisible(true);

请注意,没有单一的"Linux OS",尤其是在窗口管理方面-有很多不同的桌面环境和窗口管理器,它们在窗口排序和可见性方面的行为方式大不相同,通常是故意的

Do note that there is no single "Linux OS", especially when it comes to window management - there are lots of different desktop environments and window managers that behave in widely different ways when it comes to window ordering and visibility, often deliberately.