2017-08-11 58 views
-1

我不知道該如何居中。我試圖使用locationRelativeTo null,但gameBoard停留在左上角。 但我需要居中。如何在JFrame中居中對象

public static void main(String[] args) { 
     JFrame game = new JFrame(); 
     game.setTitle("Game2048"); 
     game.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     game.setSize(420, 700); 
     game.setResizable(false); 
     game.add(new Game2048()); 
     // help here >>>> game.setLocation();  
     game.setVisible(true); 
    } 
+0

你想在JFrame中居中的對象還是要居中在屏幕上的JFrame? – bachph

+0

只有我添加的對象。 –

+1

可能的複製到[「如何設置JFrame的出現爲中心,不管顯示器分辨率的?」(https://stackoverflow.com/questions/2442599/how-to-set-jframe-to-appear-centered-regardless-的顯示器分辨率) –

回答

1

參見方法setLocationRelativeTo(Component)的的Javadoc:

如果組件是null,或與該組件關聯的GraphicsConfigurationnull,窗口被放置在屏幕的中心。中心點可以通過GraphicsEnvironment.getCenterPoint方法獲得。

這意味着,你可以看到簡單地使用

game.setLocationRelativeTo(null); 

和你JFrame game將被放置在屏幕的中央。

1

你可以在這裏集中兩件事。首先,您可以將完整的程序窗口居中。這應該是可能的與

game.setLocationRelativeTo(null); 

第二件事居中是JFrame中的組件,在你的情況Game2048組件。因此,我可以推薦教程A Visual Guide to Layout Managers

當涉及到尺寸並不總是簡單的理解他們是如何在Swing中使用。

我建議您在組件Game2048中設置尺寸,並讓JFrame應用尺寸。

如果你用一個JPanel,你也可以使用參考setAlignment方法

panel.setAlignmentX(Component.CENTER_ALIGNMENT); 
panel.setAlignmentY(Component.CENTER_ALIGNMENT); 
1

只有對象我補充道。

然後最簡單的方法是使用GridBagLayout作爲框架的內容窗格(而不是默認的BorderLayout)。

//game.add(new Game2048()); 
game.setLayout(new GridBagLayout()); 
game.add(new Game2048, new GridBagConstraints()); 

使用默認約束將導致組件在可用空間中居中。

閱讀關於How to use GridBagLayout的Swing教程中的部分以獲取更多信息,尤其是關於使用weightx/weighty約束的部分,以瞭解其工作原理。