Hov*_*els 124 java user-interface swing
在另一个线程中,我说过我喜欢通过做这样的事情来集中我的GUI:
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HexagonGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Run Code Online (Sandbox Code Playgroud)
但安德鲁汤普森有不同的意见,而是打电话
frame.pack();
frame.setLocationByPlatform(true);
Run Code Online (Sandbox Code Playgroud)
和询问的头脑想知道为什么?
And*_*son 166
在我看来,屏幕中间的GUI看起来如此......"splash-screen'ish".我一直在等待它们消失,真正的 GUI出现!
从Java 1.5开始,我们就可以访问了Window.setLocationByPlatform(boolean).哪一个..
设置此窗口是否应显示在本机窗口系统的默认位置,或者在下次使窗口可见时显示在当前位置(由getLocation返回).此行为类似于显示的本机窗口,没有以编程方式设置其位置.如果未明确设置其位置,则大多数窗口系统会级联窗口.一旦窗口显示在屏幕上,就确定实际位置.
看一下这个示例的效果,它将3个GUI放入操作系统选择的默认位置 - 在Windows 7,Linux与Gnome和Mac OS X上.

(3批)3个整齐堆叠的图形用户界面.这代表了最终用户的"最小惊喜之路",因为它是操作系统如何定位默认纯文本编辑器的3个实例(或者其他任何东西).我要感谢Linux和Mac的trashgod.图片.
这是使用的简单代码:
import javax.swing.*;
class WhereToPutTheGui {
public static void initGui() {
for (int ii=1; ii<4; ii++) {
JFrame f = new JFrame("Frame " + ii);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
String s =
"os.name: " + System.getProperty("os.name") +
"\nos.version: " + System.getProperty("os.version");
f.add(new JTextArea(s,3,28)); // suggest a size
f.pack();
// Let the OS handle the positioning!
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
initGui();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我完全同意这setLocationByPlatform(true)是指定新JFrame位置的最好方法,但在双显示器设置中,您可以解决问题.在我的例子中,子JFrame是在"另一个"监视器上生成的.示例:我在屏幕2上有我的主GUI,我启动了一个新的JFrame,setLocationByPlatform(true)它在屏幕1上打开.所以这是一个更完整的解决方案,我认为:
...
// Let the OS try to handle the positioning!
f.setLocationByPlatform(true);
if( !f.getBounds().intersects(MyApp.getMainFrame().getBounds()) ) {
// non-cascading, but centered on the Main GUI
f.setLocationRelativeTo(MyApp.getMainFrame());
}
f.setVisible(true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23788 次 |
| 最近记录: |