GridLayout的问题无法正常工作

时间:2012-06-04 00:11:54

标签: java swing awt layout-manager grid-layout

我正在尝试为4个按钮创建一个2x2网格,用于我正在开发的会员计​​划。我遇到的问题是,不管我做什么,它只是显示为1x4网格。代码如下。

    private void buildStartupPanel()
{
    startup = new JPanel();
    startup.setLayout(new GridLayout(2,2));
    addMember = new JButton ("Add a new member");
    removeMember = new JButton ("remove Member");
    reviewMember = new JButton ("Review a Member");
    reviewAll = new JButton ("Review All Members");
    startup.add(addMember);
    startup.add(removeMember);
    startup.add(reviewMember);
    startup.add(reviewAll);
    addMember.addActionListener(this);
    removeMember.addActionListener(this);
    reviewMember.addActionListener(this);
    reviewAll.addActionListener(this);
}

输出结果时,显示以下内容

添加新会员

删除会员

审核会员

审核所有会员

而不是

添加新会员删除会员

审核会员审核所有会员

此外,如果有人可以帮我在每个按钮之间放一个空间,那就太棒了!

2 个答案:

答案 0 :(得分:4)

使用第3&第4 int到构造函数的间距。否则,似乎在这里工作得很好:

Startup Pane

import java.awt.GridLayout;
import javax.swing.*;

public class StartupPanel {

    private JComponent getStartupPanel()
    {
        JPanel startup = new JPanel();
        startup.setLayout(new GridLayout(2,2,50,5));
        JButton addMember = new JButton("Add a new member");
        JButton removeMember = new JButton("remove Member");
        JButton reviewMember = new JButton("Review a Member");
        JButton reviewAll = new JButton("Review All Members");
        startup.add(addMember);
        startup.add(removeMember);
        startup.add(reviewMember);
        startup.add(reviewAll);

        return startup;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                StartupPanel sp = new StartupPanel();
                JOptionPane.showMessageDialog(null, sp.getStartupPanel());
            }
        });
    }
}

答案 1 :(得分:2)

感谢您的回复!!来发现这是我的第二个面板,我添加到代码拼写错误(woops)并扔掉所有东西。猜猜发布完整的SSCCE的重要性。至少我学会了如何做间距!谢谢大家!