Java Reference
In-Depth Information
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("BoxLayout frame");
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.getContentPane().add(Box.createRigidArea(new Dimension(50,50)));
frame.getContentPane().add(makePanel(Color.red, 10,
Component.CENTER_ALIGNMENT));
frame.getContentPane().add(Box.createVerticalGlue());
frame.getContentPane().add(makePanel(Color.blue, 50,
Component.LEFT_ALIGNMENT));
frame.getContentPane().add(Box.createVerticalGlue());
frame.getContentPane().add(makePanel(Color.yellow, 100,
Component.RIGHT_ALIGNMENT));
frame.getContentPane().add(Box.createVerticalGlue());
frame.getContentPane().add(makePanel(Color.green, 200,
Component.LEFT_ALIGNMENT));
frame.getContentPane().add(Box.createVerticalGlue());
frame.getContentPane().add(makePanel(Color.pink, 500,
Component.CENTER_ALIGNMENT));
frame.pack();
frame.setVisible(true);
}
private static JPanel makePanel(Color col, int w, float a) {
JPanel panel = new JPanel();
panel.setBackground(col);
panel.setAlignmentX(a);
panel.setPreferredSize(new Dimension(w, 50));
panel.setMaximumSize(panel.getPreferredSize());
panel.setMinimumSize(panel.getPreferredSize());
return panel;
}
}
4.
Run the program again. Observe what happens when you resize the window now.
How It Works
This is how it works:
1.
The workings of this example should be easy to follow. First, the layout manager of the JFrame
content pane is changed to a BoxLayout .
2.
Next, a number of panels are added. You set their background colors; minimum, maximum, and
preferred sizes; and horizontal alignments using the makePanel method.
3.
Finally, in the second version of the class, Box.createRigidArea and Box.createVerticalGlue add rigid
areas and glue between stacked components. The following section shows these options in more detail.
Search WWH ::




Custom Search