按钮在行中的位置,在基于JPanel的菜单栏中排列'

时间:2016-03-03 13:54:20

标签: java swing jpanel layout-manager

我正在尝试Swing编程,但我无法做我想做的事。

我想放置一个带有2行按钮的顶部按钮,但我的情况下只有1行。

这是我的代码:

    Container contentPane = getContentPane(); 
    contentPane.setLayout(new BorderLayout());
    setMinimumSize(new Dimension(1000,500));
    setMaximumSize(new Dimension(1000,500));

    JPanel panelButton = new JPanel();
    JPanel panelTopButton = new JPanel();
    JPanel panelBottomButton = new JPanel();

    panelTopButton.add(dashboard);
    panelTopButton.add(journal);
    panelTopButton.add(myPlans);
    panelTopButton.add(myFavorites);
    panelTopButton.add(shoppingCart);

    panelBottomButton.add(profile);
    panelBottomButton.add(notifications);

    panelButton.add(panelTopButton, BorderLayout.NORTH);
    panelButton.add(panelBottomButton, BorderLayout.SOUTH);


    contentPane.add(panelButton,BorderLayout.NORTH);

    //Display
    setSize(400,120);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I have this

enter image description here

I want this

enter image description here

有人能帮助我吗?

3 个答案:

答案 0 :(得分:2)

每行需要一个面板。

尝试这样做:

JPanel panelButtonsL1 = new JPanel();
JPanel panelButtonsL2 = new JPanel();

panelButtonsL1.add(dashboard);
panelButtonsL1.add(journal);
panelButtonsL1.add(myPlans);
panelButtonsL1.add(myFavorites);
panelButtonsL1.add(shoppingCart);

panelButtonsL2.add(profile);
panelButtonsL2.add(notifications);

JPanel的默认布局为FlowLayout。请记住,布局对于使用swing组件处理非常重要。

将底部面板定义为GridLayout

JPanel panelButton = new JPanel(new GridLayout(2, 1)); // 2 rows x 1 column
panelButton.add(panelButtonsL1);
panelButton.add(panelButtonsL2);

您可以在API.

上找到GridLayout的详细信息

答案 1 :(得分:0)

您可以使用GridLayout实现这一目标:为{BALton}分配GridLayout两行一列,然后将两个面板添加到其中。

答案 2 :(得分:0)

根据您的需要,通过继续使用面板中的默认 FlowLayout ,可以获得更简单的选择。它比使用 GridLayout 更合适,因为您希望最后2个按钮移动到下一行并居中。

如果您使用 GridLayout ,则下一行的按钮可能会直接位于上方的其中一个按钮下方。以下是获得所需内容的两种方法。

方法1 。减小按住按钮的主面板的宽度: 这样,你必须使用BorderLayout.CENTER添加主面板。

enter image description here

方法2 。将按钮添加到较小宽度的子面板,并将其添加到主面板。所有按钮都将添加到较小的子面板中:

enter image description here