Java 中的多个布局管理器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2554684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Layout Managers in Java
提问by ranzy
Is there way to use more than 1 layout manager in Java. Right now I'm using a gridLayout to implement a chess board but beneath it I would like to put some other stuff but not in a gridLayout. Maybe a FlowLayout or some other layout. How would I go about doing this? Thanks!
有没有办法在 Java 中使用 1 个以上的布局管理器。现在我正在使用 gridLayout 来实现一个棋盘,但在它下面我想放一些其他的东西,但不在 gridLayout 中。也许是 FlowLayout 或其他一些布局。我该怎么做呢?谢谢!
回答by ring bearer
Yes, all you need is to plan your over all UI Layout (i.e; Window, master panel etc)
是的,您只需要规划整个 UI 布局(即;窗口、主面板等)
For example, you need to put something under your chessboard, I would normally go with a BorderLayout at the basic level.
例如,您需要在棋盘下放置一些东西,我通常会在基本级别使用 BorderLayout。
So assume I have a JPanel called masterPanel, that holds all the components for my chess app. So, code would look like:
所以假设我有一个名为 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);
回答by Michael Borgwardt
Is there way to use more than 1 layout manager in Java.
有没有办法在 Java 中使用 1 个以上的布局管理器。
Absolutely. In fact, using multiple layout managers is the norm.
绝对地。事实上,使用多个布局管理器是常态。
How would I go about doing this?
我该怎么做呢?
Any Containersubclass can have a LayoutManagerand contain child elements. And each of these child elements can itself be a Containerwith children. The most commonly used container below the top-level frames is JPanel.
所有Container子类可以有一个LayoutManager与包含子元素。并且这些子元素中的每一个本身都可以是Container带有子元素的。顶层框架下最常用的容器是JPanel.
For your example, you should probably use a BorderLayoutfor the frame, put a JPanelwith the grid in its CENTER position (because that's the one that gets all available remaining space when the other positions have been given their preferred sizes) and another JPanelwith the "other stuff" in the SOUTH position.
对于您的示例,您可能应该使用 aBorderLayout作为框架,将 aJPanel与网格放在其中心位置(因为当其他位置已被赋予其首选大小时,这是获得所有可用剩余空间的一个),另一个JPanel与“其他东西”在南位置。
More details can be found in the Swing tutorial on layout managers.

