【发布时间】:2011-09-25 23:01:19
【问题描述】:
GridLayout 的默认行为是逐行填充组件,从左到右。我想知道是否可以使用它使组件按列填充(从左到右)?谢谢。
【问题讨论】:
标签: java swing awt layout-manager grid-layout
GridLayout 的默认行为是逐行填充组件,从左到右。我想知道是否可以使用它使组件按列填充(从左到右)?谢谢。
【问题讨论】:
标签: java swing awt layout-manager grid-layout
您可以扩展 GridLayout 并仅覆盖一种方法
而不是int i = r * ncols + c; 使用int i = c * nrows + r; 我认为这就足够了。
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = rows;
int ncols = cols;
boolean ltr = parent.getComponentOrientation().isLeftToRight();
if (ncomponents == 0) {
return;
}
if (nrows > 0) {
ncols = (ncomponents + nrows - 1) / nrows;
} else {
nrows = (ncomponents + ncols - 1) / ncols;
}
int w = parent.width - (insets.left + insets.right);
int h = parent.height - (insets.top + insets.bottom);
w = (w - (ncols - 1) * hgap) / ncols;
h = (h - (nrows - 1) * vgap) / nrows;
if (ltr) {
for (int c = 0, x = insets.left ; c < ncols ; c++, x += w + hgap) {
for (int r = 0, y = insets.top ; r < nrows ; r++, y += h + vgap) {
int i = r * ncols + c;
if (i < ncomponents) {
parent.getComponent(i).setBounds(x, y, w, h);
}
}
}
} else {
for (int c = 0, x = parent.width - insets.right - w; c < ncols ; c++, x -= w + hgap) {
for (int r = 0, y = insets.top ; r < nrows ; r++, y += h + vgap) {
int i = r * ncols + c;
if (i < ncomponents) {
parent.getComponent(i).setBounds(x, y, w, h);
}
}
}
}
}
}
【讨论】:
preferredLayoutSize、minimumLayoutSize 等也这样做。
GridLayout 管理器不支持此类用例。
我建议你看看GridBagLayout,它允许你通过GridBagConstraints.gridx和GridBagConstraints.gridy设置位置。
(要获得类似于GridLayout 的行为,请务必设置权重并正确填充。)
【讨论】:
您无法通过单个GridLayout 实现此目的。但是,您可以有一个 GridLayout 一行,每个单元格都有一个 GridLayout 一个包含多行的单列。尽管使用像 TableLayout 这样的不同 LayoutManager 可能是更简单的选择。
【讨论】:
我建议你试试MigLayout。您可以通过以下方式切换流向:
setLayout(new MigLayout("flowy"));
add(component1);
add(component2);
add(component3, "wrap");
add(component4);
add(component5);
add(component6);
使用 MigLayout 有很多方法可以实现这一点,我发现它比 GridBagLayout 更友好,而且功能同样强大,甚至更多。您将不再需要 BorderLayout、FlowLayout、BoxLayout 等,MigLayout 也可以。
【讨论】:
你可以重新计算每个组件的位置:
Int row = ROWS;//amount of ROWS in the grid
Int col = COLUMs;//amount of COLUMS in the grid
Int x = i / row;// i is the component index(0,1,2,3...)
Int y = i - x * row;
Int position=col * x + y;
Panel.add(component, position);//the panel with gridlayout
您可能需要最初填充面板以避免在不存在的位置上出现 nullPointer:
For(i=0 to i= ROWS){
For(j =0 to j=columns){
Panel.add(new ...(random component)
}
}
【讨论】: