如何在java中的边框布局中嵌入网格布局

时间:2012-04-14 17:17:40

标签: java swing grid-layout

我有边框布局,我想在中心部分添加网格布局。但是,我无法声明网格,然后将其添加到我的中心边框。我怎么能这样做?

public Liability_Calculator(String s)
{
    super(s);
    setSize(325,200);

    c = getContentPane();
    c.setLayout(new BorderLayout());

    //the top label
    total = new JLabel("Total monthly liabilities ", JLabel.CENTER);
    c.add(total, BorderLayout.NORTH);


    //the grid
    GridLayout grid = new GridLayout(2,2);

    text_field1 = new JTextField(7);

    //I GET AN ERROR HERE!!!!!!!
    grid.add(text_field1);

    //AND ERROR HERE!!!!!!!!!!!!!
    c.add(grid, BorderLayout.CENTER);




    setVisible(true);
}

2 个答案:

答案 0 :(得分:7)

您正在尝试将组件添加到布局,而这根本无法完成。而是使用JPanel,给它一个GridLayout,然后将组件添加到JPanel(在这里充当“容器”)。

通常,您需要使用GUI的最佳布局来嵌套每个JPanels,这里使用GridLayout的内部JPanel和使用BorderLayout的外部JPanel。然后,您只需将内部JPanel添加到BorderLayout.CENTER位置的外部JPanel(此处为contentPane)。

答案 1 :(得分:0)

即使您这是很久以前回答的问题。 这是我的解决方案。我只想在我的答案中提供代码可视化,该答案源于Hovercraft必须说的话。

public class Display extends JFrame
{

JPanel gridHolder = new JPanel(); // panel to store the grid
private GridLayout buttonsGrid; // space containing a buttons
private JButton myButtons[]; // grid is to be filled with these buttons
private BorderLayout mainGUILayout; // main gui layout
private Container mainGuiContainer;

public Display()
{
    mainGUILayout = new BorderLayout(5,5); // the width of space in between the main gui elements.
    mainGuiContainer = getContentPane(); // getting content pane
    mainGuiContainer.setLayout(mainFrameLayout); // setting main layout
    buttonsGrid = new GridLayout(4, 1, 5, 5); // 4 buttons one over the other
    myButtons = new JButton[4]; // player's hand represented with buttons
    gridHolder.setLayout(buttonsGrid);

                for (int x = 0; x < 4; x++)
                {

                myButtons[x] = new JButton (" ");
                gridHolder.add(myButtons[x]);
                }

            add(gridHolder, BorderLayout.WEST);
            setVisible(true);
}
}



public class MainGUILaunch
{
    public static void main (String args[])
    {
        Display myApplication = new Display();
        myApplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myApplication.setSize(1024, 1024);
        myApplication.setVisible(true); // displaying application
    }
} // End of MainGUILaunch