2011-08-22 29 views
114

another thread我說,我喜歡做這樣的事情,以中心我的GUI:如何最好地定位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); 

但安德魯·湯普森有不同的意見,改爲調用

frame.pack(); 
frame.setLocationByPlatform(true); 

和好奇之心想知道爲什麼?

+1

無關:你可以幫我一個忙通過看這[問題](https://stackoverflow.com/questions/46033958/java-switch-camera-front-back)。我認爲少數情況下,內容應該得到更多的下/關票... – GhostCat

回答

152

在我看來,屏幕中間的GUI看起來很「.. splash-screen'ish」。我一直在等待它們消失,並且真實 GUI出現!

自Java 1.5以來,我們訪問了Window.setLocationByPlatform(boolean)。這..

設置此窗口是否應該出現在了本機窗口系統或在當前位置(由getLocation返回)窗口可見下一次的默認位置。此行爲類似於不以編程方式設置其位置的本地窗口。 大多數窗口系統級聯窗口,如果他們的位置沒有明確設置。一旦窗口顯示在屏幕上,就會確定實際位置。

看一看這個例子是把3個圖形用戶界面在默認位置由OS作爲選擇的效果 - 在Windows 7,Linux的使用GNOME & Mac OS X的

Stacked windows on Windows 7enter image description here Stacked windows on Mac OS X

(3手)3個圖形用戶界面整齊堆疊。這代表着最終用戶的「最少驚喜之路」,因爲操作系統可能如何定位默認純文本編輯器的3個實例(或者其他任何東西)。我感謝Linux & Mac的垃圾內容。圖片。

下面是使用簡單的代碼:

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(); 
      } 
     }); 
    } 
} 
+1

@AndrewThompson爲什麼你的計數器變量'ii'而不僅僅是'i'?這是否遵守某種慣例或者是個人喜好(或者完全不同)? – MirroredFate

+1

@MirroredFate嗯..我想我會鎖定選項3,「完全不同的東西」。這正是我第一次使用Basic編程時習慣的(很久以前)。懶惰它是繼續使用的原因,「如果它沒有壞掉,不要修復它」。 –

+1

@MirroredFate你有任何機會波斯王子範?我很抱歉把它放在這裏。我只是無法抵抗 – Anarach

1

我完全同意,setLocationByPlatform(true)是指定一個新的JFrame的位置最好的方式,但在雙顯示器設置你可以進入的問題。在我的情況下,孩子JFrame是在'另一個'顯示器上產生的。例如:我有我的屏幕2主界面,我開始setLocationByPlatform(true)一個新的JFrame和它打開的屏幕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);