Java Reference
In-Depth Information
for (int i=0,n=labels.length; i<n; i++) {
JButton button = new JButton(labels[i]);
button.setAlignmentY(alignment);
container.add(button);
}
return container;
}
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel1 = makeIt("Top", Component.TOP_ALIGNMENT);
Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
Container panel3 = makeIt("Bottom", Component.BOTTOM_ALIGNMENT);
frame.setLayout(new GridLayout(1, 3));
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.setSize(423, 171);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Laying Out Components with Different Alignments
Working with small components that have the same alignment is relatively simple. However,
if the components in a container managed by a
BoxLayout
have different alignments, things
become more complex. In addition, the components won't necessarily be displayed the way
you might expect. For a vertical box, the components appear as follows:
If a component has its x alignment set to
Component.LEFT_ALIGNMENT
, the left edge of the
component will be aligned with the center of the container.
•
•
If a component has its x alignment set to
Component.RIGHT_ALIGNMENT
, the right edge of
the component will be aligned with the center of the container.
If a component has its x alignment set to
Component.CENTER_ALIGNMENT
, the component
will be centered within the container.
•
•
Other alignment values cause components to be placed in varying positions (depending
on the value) relative to the center of the container.