Karen
Karen

Reputation: 275

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

Upvotes: 7

Views: 77400

Answers (4)

smkelsey
smkelsey

Reputation: 1

It's this one.

buttonPanel = new JPanel();
buttonPanel.setSize(new Dimension(30, 100));

Don't let the layout manager adjust your sizes.

Upvotes: -2

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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.

Upvotes: 10

Jill
Jill

Reputation: 539

also- that is the preferred size. if you don't want to allow resizing, you can also set the maximum sizes as well.

if you're able, you may want to check out the MIG layout, but BoxLayout is also easy to use and in the java toolkit already.

Upvotes: 0

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45324

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

Upvotes: 1

Related Questions