2010-03-31 87 views
5

有沒有辦法在Java中使用多於1個佈局管理器。現在,我正在使用一個gridLayout來實現一個棋盤,但在它下面我想放一些其他的東西,但不是在一個gridLayout。也許是一個FlowLayout或其他佈局。我會如何去做這件事? 謝謝!Java中的多個佈局管理器

回答

6

有沒有辦法在Java中使用多於1個佈局的 manager。

絕對。實際上,使用多個佈局管理器是常態。

我該如何去做這件事?

任何Container子類可以有一個LayoutManager幷包含子元素。並且這些子元素中的每一個本身都可以是帶孩子的Container。頂級框架下面最常用的容器是JPanel

對於你的榜樣,你應該使用BorderLayout爲框架,把JPanel在其中心位置的網格(因爲這是一個得到所有可用的剩餘空間時,其他位置都被賦予了他們的首選尺寸)另一個JPanel與南方的「其他東西」位置。

更多詳細信息請參見Swing tutorial on layout managers

7

是的,所有你需要的是計劃你在所有的UI佈局;

例如,你需要把一些你的棋盤下(即窗口,主面板等),我通常會用一個BorderLayout的,在去基本的水平。

因此,假設我有一個名爲masterPanel的JPanel,它包含我的國際象棋應用程序的所有組件。因此,代碼將如下所示:

JPanel masterPanel = new JPanel(new BorderLayout()); 
JPanel chessBoardPanel = createChessboardPanel(); //assuming this method will return a 
//JPanel with chess board using GridLayout 
JPanel infoPanel = new JPanel(); //this is the panel that would contain info elements, that //may go below my chess board. 
//Now add everything to master panel. 
masterPanel.add(chessBoardPanel, BorderLayout.CENTER); 
masterPanel.add(infoPanel, BorderLayout.PAGE_END); 
//add masterPanel to your window (if required) 
this.getContentPane().add(masterPanel);