Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the size of panels

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);            
}
}
like image 419
Karen Avatar asked Oct 20 '09 12:10

Karen


2 Answers

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.

like image 126
Michael Borgwardt Avatar answered Oct 05 '22 21:10

Michael Borgwardt


It looks like you're using a GridLayout, or perhaps a FlowLayout, neither being what you want. You probably want to use a BoxLayout, which respects its components preferred sizes.

final JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(leftPanel);
p.add(mainPanel);
p.add(rightPanel);
like image 28
Jonathan Feinberg Avatar answered Oct 05 '22 21:10

Jonathan Feinberg