Java Prevent BoxLayout From Expanding Children

I have created design GUI using java by programmatically. I want to add some of JPanel to my JFrame (mainwindow). I set JFrame layout using BoxLayout. I am use BoxLayout because want the children resize only width. But, when I resize the mainwindow (JFrame), children width and height is resized. BoxLayout expanding all children width and height.

This is code to add JPanel to my JFrame using BoxLayout :

JPanelProgress panel1 = new JPanelProgress();
panel1.setBackground(Color.red);

JPanelProgress panel2 = new JPanelProgress();
panel2.setBackground(Color.green);

JPanelProgress panel3 = new JPanelProgress();
panel3.setBackground(Color.yellow);

BoxLayout boxlayout = new BoxLayout(jPanel1, BoxLayout.Y_AXIS);
jPanel1.setLayout(boxlayout);
jPanel1.add(panel1);
jPanel1.add(panel2);
jPanel1.add(panel3);

Output using this code is like this :

java_jframe_resized_01Alternatively, we can use Box.Filler prevent BoxLayout resized the childen height. I have modified my code like this :

JPanelProgress panel1 = new JPanelProgress();
panel1.setBackground(Color.red);

JPanelProgress panel2 = new JPanelProgress();
panel2.setBackground(Color.green);

JPanelProgress panel3 = new JPanelProgress();
panel3.setBackground(Color.yellow);

BoxLayout boxlayout = new BoxLayout(jPanel1, BoxLayout.Y_AXIS);
jPanel1.setLayout(boxlayout);
jPanel1.add(panel1);
jPanel1.add(panel2);
jPanel1.add(panel3);

//prevent all child height resized
jPanel1.add(new Box.Filler(new Dimension(0, 0), 
        new Dimension(0, Short.MAX_VALUE), new Dimension(0, Short.MAX_VALUE)));

The result using this modified code (prevent BoxLayout expanding all children) is like this :

java_jframe_resized_02Add Box.Filler to our BoxLayout prevent all children expanding they height.

Source : http://stackoverflow.com/questions/14010864/keep-boxlayout-from-expanding-children

Add a Comment

Your email address will not be published. Required fields are marked *