Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a grid layout inside a border layout in java

I have a border layout and I want to add a grid layout to the center section. However, I can't declare a grid and then add my center border. How can I do this?

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);
}
like image 257
DannyD Avatar asked Apr 14 '12 17:04

DannyD


2 Answers

You're trying to add a component to a layout, and that simply cannot be done. Instead use a JPanel, give it a GridLayout, and then add the component to the JPanel (acting as the "container" here).

In general, you will want to nest JPanels with each using the best layout for the GUI, here the inner JPanel using GridLayout and the outer one using BorderLayout. Then you simply add the inner JPanel to the outer one (here your contentPane) in the BorderLayout.CENTER position.

like image 199
Hovercraft Full Of Eels Avatar answered Sep 28 '22 02:09

Hovercraft Full Of Eels


Providing code visualization derived from Hovercraft's answer:

Display class:

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 class:

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
like image 27
Ivan Avatar answered Sep 28 '22 00:09

Ivan