如何将面板拆分为子面板?

时间:2012-10-29 17:47:33

标签: java swing layout jpanel panel

我已经制作了一个面板(它是一排按钮),并且它位于框架的底部(SOUTH),但是我想在它下面添加两行(面板/子面板)(文本输入)线和输出线如果重要的话)。现在我唯一知道要做的就是声明并添加更多面板,这很好,但是当我指定.SOUTH时,它们会超越前一个面板。

编辑:我使用的解决方案

正如Ted Hopp建议的那样,我将原始面板(现在称为subPanel1)以及原始面板(subPanel2& subPanel3)上的两个新面板添加到第四个“容器面板”( bottomCotainerPanel)。由于我只有三个子面板,这允许我指定每个子面板在containerPanel中的位置(使用NORTH,CENTER,SOUTH,如果你有超过3个,可能必须做一些稍微不同的事情),然后指定在哪里contianerPanel会进入框架(SOUTH)。

    subPanel1.setLayout(new GridLayout(1,6)); //Layout of subPanel1
subPanel1.add(clearButton);
subPanel1.add(customerNameLabel);
subPanel1.add(customerNameTextField);
subPanel1.add(showByNameButton);
subPanel1.add(openNewSavingsButton);
subPanel1.add(openNewCheckingButton);


subPanel2.add(sendChatTextField);
subPanel2.add(sendButton);
subPanel2.add(clearButton2);

subPanel3.add(receiveChatTextField);
subPanel3.add(nextButton);
subPanel3.add(previousButton);

bottomContainerPanel.setLayout(new GridLayout(3,1));   //Layout of Container Panel
bottomContainerPanel.add(subPanel1, BorderLayout.NORTH);
bottomContainerPanel.add(subPanel2, BorderLayout.CENTER);
bottomContainerPanel.add(subPanel3, BorderLayout.SOUTH);

tellerWindow.getContentPane().add(bottomContainerPanel, BorderLayout.SOUTH);

3 个答案:

答案 0 :(得分:4)

您需要添加一个容器面板作为框架的SOUTH面板。容器本身应该具有您想要的底部所有内容的布局。

答案 1 :(得分:2)

如果您只想将面板拆分为南北两个相等的部分,请使用GridLayout。如果你想要中间的东西,你可以使用BorderLayout

如果您想让用户更改子面板的大小,请使用JSplitPane

答案 2 :(得分:0)

我在尝试将几行按钮放入从ListDemo示例中借用的面板时遇到了类似的问题。好吧,首先要做的是阅读BorderLayoutHow to Use BorderLayout,或至少看到那里显示的图像:
enter image description here

BorderLayout中不能有多个底行。但您可以使用嵌套布局。我们需要的是BoxLayout,请参阅How to Use BoxLayout
enter image description here

我们只需用按钮行替换上图中显示的按钮。

public class MyStuff extends JPanel {
  ...
  public MyStuff() {
    super(new BorderLayout());
    ...
    JPanel buttonArea = new JPanel();
    buttonArea.setLayout(new BoxLayout(buttonArea, BoxLayout.PAGE_AXIS));
    add(buttonArea, BorderLayout.PAGE_END);
    ...
    //if you dislike the default center alignment:
    //panelWithButtons1.setAlignmentX(Component.LEFT_ALIGNMENT);
    buttonArea.add(...);// add the 1st panel with buttons
    buttonArea.add(...);// add the 2nd panel with buttons
    buttonArea.add(...);// add the 3rd panel with buttons