views:

170

answers:

1

Here is my code:

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

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel();
        firstPanel.setLayout(new GridLayout(4, 4));
        firstPanel.setMaximumSize(new Dimension(4*100, 4*100));
        firstPanel.setMinimumSize(new Dimension(4*100, 4*100));
        JButton btn;
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                btn = new JButton();
                btn.setPreferredSize(new Dimension(100, 100));
                firstPanel.add(btn);
            }
        }

        mainPanel.add(firstPanel);
        frame.add(mainPanel);

        frame.setSize(520,600);
        //frame.setMinimumSize(new Dimension(520,600));
        frame.setVisible(true);
    }
}

When I increase the size of the window (by mouse) I see that my panel does not increase its size. It is the expected behavior (because I set the maximal size of the panel). However, when I decrease the size of the window, I see that width of the panel is decreased too (while the height is constant).

So, the setMinimumSize works only partially. Why is that?

+3  A: 

As discussed in How to Use BoxLayout: Box Layout Features, this is the expected behavior for a top-to-bottom box layout, BoxLayout.Y_AXIS. Change the axis to a left-to-right box layout, BoxLayout.X_AXIS, and you'll see the heights shrink instead. See How to Use BoxLayout: Specifying Component Sizes for more details.

trashgod