set 和 的固定单元格的 set 和 to 。对于设置为 的浮动单元格,对于应仅水平扩展的浮动单元格,设置为 的浮动单元格,对于设置为 的垂直扩展单元格。weightx
weighty
GridBagConstraints
0
fill
NONE
fill
BOTH
weightx
1
weighty
1
单元格仅在包含任何内容时才会扩展,因此您需要用某些内容填充它。我选择了s并为固定单元格中的标签设置了固定尺寸。调整大小时,您需要重新计算尺寸并调用以重新计算布局。JLabel
invalidate()
下面是一个 x 网格的示例:w
h
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GridBag {
public static void main(String[] args) {
final JFrame f = new JFrame("Gridbag Test");
final Container c = f.getContentPane();
c.setLayout(new GridBagLayout());
final Dimension dim = new Dimension(70, 70);
final int w = 4;
final int h = 4;
final JLabel[] yfloating = new JLabel[w];
final JLabel[] xfloating = new JLabel[h];
final JLabel[][] fixed = new JLabel[w][h];
// adding the vertically floating cells
final GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 0.0;
gc.weighty = 1.0;
for(int i = 0; i < w; ++i) {
yfloating[i] = new JLabel("floating " + i);
yfloating[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
yfloating[i].setHorizontalTextPosition(JLabel.CENTER);
yfloating[i].setVerticalTextPosition(JLabel.CENTER);
gc.gridy = 0;
gc.gridx = i+1;
c.add(yfloating[i], gc);
}
// adding the horizontally floating cells
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gc.weighty = 0.0;
for(int i = 0; i < w; ++i) {
xfloating[i] = new JLabel("floating " + i);
xfloating[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
xfloating[i].setHorizontalTextPosition(JLabel.CENTER);
xfloating[i].setVerticalTextPosition(JLabel.CENTER);
gc.gridy = i+1;
gc.gridx = 0;
c.add(xfloating[i], gc);
}
// adding the fixed cells
gc.fill = GridBagConstraints.NONE;
gc.weightx = 0.0;
gc.weighty = 0.0;
for(int i = 0; i < w; ++i) {
for(int j = 0; j < h; ++j) {
fixed[i][j] = new JLabel("fixed " + i);
fixed[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
fixed[i][j].setMaximumSize(dim);
fixed[i][j].setMinimumSize(dim);
fixed[i][j].setPreferredSize(dim);
gc.gridx = i+1;
gc.gridy = j+1;
c.add(fixed[i][j], gc);
}
}
c.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
final Component comp = e.getComponent();
final int newSize = Math.min(comp.getHeight() / h, comp.getWidth() / w);
final Dimension newDim = new Dimension(newSize, newSize);
for(int i = 0; i < w; ++i) {
for(int j = 0; j < h; ++j) {
fixed[i][j].setMaximumSize(newDim);
fixed[i][j].setMinimumSize(newDim);
fixed[i][j].setPreferredSize(newDim);
}
}
comp.invalidate();
}
});
f.pack();
f.setVisible(true);
}
}