14. 89. 4. FlowLayout :JPanel的默认布局管理器 |
|
- A FlowLayout adds components to the container in rows.
- When it can't fit more components in a row, it starts a new row.
- Components within a FlowLayout-managed container are given their preferred size.
- If there is insufficient space, you do not see all the components.
|
There are three constructors for creating the FlowLayout layout manager: |
public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment, int hgap, int vgap)
|
|
If an alignment is not specified, default is centered. The setting is controlled by one of the following constants: |
- FlowLayout.LEFT. Left-justify component rows.
- FlowLayout.RIGHT. Right-justify component rows.
- FlowLayout.CENTER. Center component rows.
- FlowLayout.LEADING. Justify component rows to the leading edge of the container's orientation, e.g. to the left in the left-to-right orientation.
- FlowLayout.TRAILING. Justify component rows to the trailing edge of the container's orientation, e.g. to the right in the left-to-right orientation.
|
- You can specify the gaps, in pixels, both horizontal (hgap) and vertical (vgap).
- The horizontalGap argument determines the distance between two components in the same row and between the components and the container border.
- The verticalGap argument determines the distance between components in adjacent rows and the components and the container border.
- The default for both horizontalGap and verticalGap is 5 unit.
- Negative gaps place component on top of one another.
|
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
public class FlowLayoutComponentOrientationRIGHT_TO_LEFT extends JFrame {
public FlowLayoutComponentOrientationRIGHT_TO_LEFT() {
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new JButton("OK"));
getContentPane().add(new JButton("Cancel"));
applyOrientation(this, ComponentOrientation.RIGHT_TO_LEFT);
}
public static void main(String[] argv) {
JFrame frame = new FlowLayoutComponentOrientationRIGHT_TO_LEFT();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void applyOrientation(Component c, ComponentOrientation o) {
c.setComponentOrientation(o);
if (c instanceof JMenu) {
JMenu menu = (JMenu) c;
int ncomponents = menu.getMenuComponentCount();
for (int i = 0; i < ncomponents; ++i) {
applyOrientation(menu.getMenuComponent(i), o);
}
} else if (c instanceof Container) {
Container container = (Container) c;
int ncomponents = container.getComponentCount();
for (int i = 0; i < ncomponents; ++i) {
applyOrientation(container.getComponent(i), o);
}
}
}
}
|
|