java JPanel How to fixed sizes

ManInMoon picture ManInMoon · Nov 12, 2013 · Viewed 42k times · Source

I want to have a resizable panel, that always has the top green panel of a fixed depth. i.e. all changes in height should effect the yellow panel only.

My code below is almost OK, except the green panel varies in size a little.

How do I do this?

            Panel.setLayout(new BoxLayout(Panel, BoxLayout.Y_AXIS));
        Panel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JPanel TopPanel = new JPanel();
        TopPanel.setPreferredSize(new Dimension(80,150));
        TopPanel.setVisible(true);
        TopPanel.setBackground(Color.GREEN);
        JPanel MainPanel = new JPanel();
        MainPanel.setPreferredSize(new Dimension(80,750));
        MainPanel.setVisible(true);
        MainPanel.setOpaque(true);
        MainPanel.setBackground(Color.YELLOW);

        Panel.add(TopPanel);
        Panel.add(MainPanel);

enter image description here

Answer

jzd picture jzd · Nov 12, 2013

Your question didn't restrict the solution to a BoxLayout, so I am going to suggest a different layout manager.

I would attack this with a BorderLayout and put the green panel in the PAGE_START location. Then put the yellow panel in the CENTER location without a preferredSize call.

http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

Here is an SSCCE example of the solution:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestPad extends JFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout());

        JPanel green = new JPanel();
        green.setPreferredSize(new Dimension(80, 150));
        green.setBackground(Color.GREEN);

        JPanel yellow = new JPanel();
        yellow.setBackground(Color.YELLOW);

        frame.getContentPane().add(green, BorderLayout.PAGE_START);
        frame.getContentPane().add(yellow, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}