Setting the size of panels

Karen picture Karen · Oct 20, 2009 · Viewed 61.9k times · Source

I have 3 panels. One is the main panel which holds 2 smaller panels.

For the main panel, I used

setPreferredSize(new Dimension(350, 190));

For the smaller left panel, I used

setPreferredSize(new Dimension(100, 190));

For the smaller right panel, I used

setPreferredSize(new Dimension(250, 190));

but the smaller panels remain the same size. How can I fix this?alt text

This is the code I have in my main Panel.

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

public class Panel extends JPanel
{

public Panel(Prison prison)
{
    setup();
    build(prison);
}

private void setup()
{
    setBorder(BorderFactory.createLineBorder(Color.blue));
    setLayout(new BorderLayout(1, 1));
    setPreferredSize(new Dimension(350, 190));
}

private void build(Prison prison)
{
    JTabbedPane tab = new JTabbedPane();       
    tab.addTab("Input", null, new InputPanel(), "Input");
    tab.addTab("Display", null, new DisplayPanel(), "Display");
    add(tab);            
}
}

Answer

Michael Borgwardt picture Michael Borgwardt · Oct 20, 2009

Don't do this.

The whole point of layout managers is to allow dynamic resizing, which is necessary not just for user-resizable windows but also changing texts (internationalization) and different default font sizes and fonts.

If you just use the layout managers correctly, they will take care of panel sizes. To avoid having your components stretched out all over the screen when the user increases the window size, have an outermost panel with a left-aligned FlowLayout and the rest of the UI as its single child - that will give the UI its preferred size and any surplus is filled with the background color.