如前所述,我不是嵌套面板的忠实拥护者(不再是,因为我发现了强大且易于掌握的第三方管理器 :-) 我目前最喜欢的是 MigLayout,所以这里是一体式的版本:
垂直线突出了嵌套布局确实存在的一个臭名昭著的问题:不支持跨面板对齐(尽管有一些技巧可以实现)。我的建议是学习掌握三巨头之一(MigLayout、JGoodies FormLayout、DesignGridbagLayout),然后在没有嵌套的情况下进行大多数布局。
MigLayout layout = new MigLayout(
// auto-wrap after 4 columns
"wrap 5",
// 5 columns:
// 1. labels, 2./3. radiobuttons,
// 4. buttons, 5. tabbedPane
"[][fill, sg][fill, sg]u[fill]para[fill, grow]",
// 7 rows:
// 1. - 6. default for combos/buttons,
// 7. growing table
// > 7 default
// unrelated gaps before/after the table
"[][][]u[][][][grow, fill]u[]r[]");
JComponent content = new JPanel(layout);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("SomeTab", new JPanel());
String[] labels = { "Company:", "Product Type:", "Product:" };
for (String string : labels) {
JLabel label = new JLabel(string);
JComboBox combo = new JComboBox();
content.add(label);
if (string.equals(labels[0])) {
content.add(combo, "span 2");
// make span all rows,
// force a min width
content.add(tabbedPane, "skip 1, spany, grow, wmin 500");
} else {
content.add(combo, "span 2, wrap");
}
};
// JXTable supports specifying the visibleRowCount
JXTable table = new JXTable(0, 1);
table.setVisibleRowCount(10);
content.add(new JScrollPane(table), "span 3, spany 4, grow");
String[] buttons = {"Add", "Remove", "Edit"};
for (String string : buttons) {
content.add(new JButton(string));
}
content.add(new JLabel("Search:"), "newline, skip 2");
JTextField field = new JTextField(12);
content.add(field, "span 2");
content.add(new JLabel("Show only:"), "newline");
String[] checks = {"A", "B", "C"};
String skip = "";
for (String string : checks) {
content.add(new JCheckBox(string), skip);
content.add(new JRadioButton(string.toLowerCase()), "wrap");
skip = "skip";
}
// decorate to show vertical alignment line
DebugLayerUI ui = new DebugLayerUI(field);
JLayer layer = new JLayer(content, ui);
// just for fun, a layerUI which can be used to debug component alignement
public class DebugLayerUI extends LayerUI {
private Map<JComponent, Integer> markThem;
public DebugLayerUI(JComponent child) {
markThem = new HashMap<>();
markThem.put(child, SwingConstants.VERTICAL);
}
public void add(JComponent child, int direction) {
markThem.put(child, direction);
}
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
g.setColor(Color.MAGENTA);
for ( Entry<JComponent, Integer> entry : markThem.entrySet()) {
JComponent child = entry.getKey();
if (SwingConstants.VERTICAL == entry.getValue()) {
Point p = SwingUtilities.convertPoint(child,
new Point(0, 0),
c);
g.drawLine(p.x, 0, p.x, c.getHeight());
} else if (SwingConstants.HORIZONTAL == entry.getValue()) {
int baseline = child.getBaseline(child.getWidth(), child.getHeight());
if (baseline > 0) {
Point p = SwingUtilities.convertPoint(child,
new Point(0, baseline), c);
g.drawLine(0, p.y, c.getWidth(), p.y);
}
}
}
}
}