更新时间:2022-04-16 22:12:55
让我们澄清一些事情.LayoutManager
由 Container
(例如 Frame
、Panel
或 Applet
)使用code>) 来计算 Container
中组件的位置和大小.这意味着谈论嵌套 LayoutManager
s"是不正确的.另一方面,您可以将 Container
嵌套在彼此内部,并为每个容器提供自己的 LayoutManager
.我相信这就是你想要做的.
Let's clarify a few things. A LayoutManager
s are used by a Container
(such as Frame
, Panel
, or Applet
) to calculate position and size of the components inside the Container
. This means that it is incorrect to talk about "nesting LayoutManager
s". On the other hand you can nest Container
s inside each other and give each one its own LayoutManager
. I believe this is what you want to do.
让我用一个人为的例子来说明这一点:
Let me illustrate this with a contrived example:
public class MyGUI {
public static void main(String[] args) {
Frame f = new Frame("Layout Example");
Panel mainPanel = new Panel(new BorderLayout());
f.add(mainPanel);
Panel toolBar = new Panel(new FlowLayout());
toolBar.add(new Button("Button 1"));
toolBar.add(new Button("Button 2"));
mainPanel.add(tollBar.NORTH);
Panel statusBar = new Panel(new FlowLayout());
statusBar.add(new Label("Status"));
mainPanel.add(statusBar);
f.pack();
f.show();
}
}
请注意,您需要为每个 LayoutManager
创建一个新的 Panel
.或者更确切地说,您创建的每个 Panel
都需要一个 LayoutManager
.此外,通过将 Frame
替换为 JFrame
,将 Panel
替换为 JPanel
,可以轻松地将这个示例从 AWT 更改为 Swing,Button
带有 JButton
,Label
带有 JLabel
.
Notice that you need to create a new Panel
for each LayoutManager
. Or rather each Panel
that you create needs a LayoutManager
. Also, this example can easily be changed from AWT to Swing by replacing Frame
with JFrame
, Panel
with JPanel
, Button
with JButton
, and Label
with JLabel
.
附言上面的代码没有经过测试.不过,它应该说明这里涉及的概念.
p.s. The above code is not tested. It should illustrate the concepts involved here, though.