6

我有一个边框布局,我想在中心部分添加一个网格布局。但是,我不能声明一个网格,然后添加我的中心边框。我怎样才能做到这一点?

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);
}
4

2 回答 2

8

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

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

于 2012-04-14T17:21:56.443 回答
2

提供源自 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); // Border layout option
    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);     }     }

MainGUILaunch 类:

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
于 2019-12-14T15:11:38.717 回答