Search code examples
javauser-interfacegridlayoutmanager

Put containers within Grid Layout


I am relatively new to programming java GUI's and I wanted to use the grid layout and put a container within that grid layout. I am not really sure how to do it but here is what I tried and it didn't work:

    Container pane = getContentPane();
    pane.setLayout(new GridLayout(3, 1));
    Container inp = getContentPane();
    inp.setLayout(new GridLayout(2, 4));
    Container out = getContentPane();
    out.setLayout(new GridLayout(1, 1));
    Container bottom = getContentPane();
    bottom.setLayout(new GridLayout(1, 2));

    pane.add(inp);
    pane.add(out);
    pane.add(bottom);

    inp.add(cn1);
    inp.add(cnum1);
    inp.add(cn2);
    inp.add(cnum2);
    inp.add(add);
    inp.add(sub);
    inp.add(mul);
    inp.add(div);

    out.add(ans);

    bottom.add(clear);
    bottom.add(exit);

    pane.add(inp);
    pane.add(out);
    pane.add(bottom);

I know that this is wrong but I hope someone can help me. Thanks!


Solution

  • All your panels are the same thing, they reference the contentPane. A component can only reside within a single container, so each time you add any of yr panels to another container, they are first removed from the parent container.

    Having said that, you should have had an exception stating that a container can't be added to itself.

    Instead, you need to do something more like...

    Container pane = getContentPane();
    pane.setLayout(new GridLayout(3, 1));
    Container inp = new JPanel(new GridLayout(2, 4));
    Container out = new JPanel(new GridLayout(1, 1));
    Container bottom = new JPanel(new GridLayout(1, 2));