我对GridBagLayout有一个非常奇怪的问题,布局似乎"调整"网格位置使组件在整齐的列中对齐 - 正是我不想要的。我希望我的组件以砖墙方式对齐,但我得到一个棋盘布局。
此示例重现案例:
public class GBLayout extends JPanel {
public GBLayout() {
setLayout(new GridBagLayout());
for (int y=0; y<10; ++y) {
int offset = y & 1;
if (offset != 0) {
GridBagConstraints c = new GridBagConstraints(
0, y, // x, y
1, 1, // w, h
0D, 0D,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2),
0, 0);
add(new JLabel("!"), c);
}
for (int x=0; x<10; ++x) {
int bx = x * 2 + offset;
int by = y;
JButton b = new JButton("(" + bx + ", " + by + ")");
GridBagConstraints c = new GridBagConstraints(
bx, by, // x, y
2, 1, // w, h
1D, 0D,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2),
0, 0);
add(b, c);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GBLayout panel = new GBLayout();
JFrame frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
目前看起来如何:
预期布局是一堵砖墙(大约,我手动编辑):
在最左边的专栏中,只有在GridBagLayout似乎对我的组件放置位置有自己的想法之后才会听从。是什么导致这种情况,我该如何解决它?
答案 0 :(得分:3)
这会给你带来理想的效果,在我的电脑上看起来像这样:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GBLayout extends JPanel {
public GBLayout() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWeights = new double[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
setLayout(gridBagLayout);
for (int y=0; y<10; ++y) {
int offset = y & 1;
if (offset != 0) {
GridBagConstraints c = new GridBagConstraints(
0, y, // x, y
1, 1, // w, h
0D, 0D,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2),
0, 0);
add(new JLabel("!"), c);
}
for (int x=0; x<10; ++x) {
int bx = x * 2 + offset;
int by = y;
JButton b = new JButton("(" + bx + ", " + by + ")");
GridBagConstraints c = new GridBagConstraints(
bx, by, // x, y
2, 1, // w, h
1D, 1D,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2),
0, 0);
add(b, c);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GBLayout panel = new GBLayout();
JFrame frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
诀窍是将表columnWeights设置为1,因为没有它,colums可以有不同的大小,一些列可以拉伸到按钮宽度,或者粉碎到0。