我试图帮助其他用户,我遇到了一个问题,我想用GridBagLayout做这个:
c1 | c2 | c3
~10% | ~80% | ~10%
v v
|-------------------------------------------------|
r1 | B1 | <S1>
~50% |-------------------------------------------------|
---->
|--------------------------------------------------|
r2 <S2> | B2 |
~50% |--------------------------------------------------|
具体问题是我想将c2的重量设置为80%,但我没有c2 中存在的组件(设置B1或B2的重量不会产生所需的效果,因为它们也分别存在于c1和c3中。
有没有办法指定网格约束没有添加不可见的组件或细分面板?看了Javadoc之后,我猜不到,但我想我还是会为后人发布这个问题。
MCVE:
public class StaggerTest {
public static void main(String[] args) {
JFrame frame = new JFrame("Stagger Test");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
placeComp(new JButton("1"), panel, 0, 0, 2, 1, 0, 0); // B1
placeComp(Box.createHorizontalStrut(10), panel, 2, 0, 1, 1, 0.1, 0.5); // S1
placeComp(Box.createHorizontalStrut(10), panel, 0, 1, 1, 1, 0.1, 0.5); // S2
placeComp(new JButton("2"), panel, 1, 1, 2, 1, 0, 0); // B2
// TODO: Is there another way, outside subdividing panel?
placeComp(Box.createGlue(), panel, 1, 2, 1, 1, 0.8, 0);
frame.setContentPane(panel);
frame.setVisible(true);
}
public static void placeComp(Component comp, JPanel panel, int x, int y, int w, int h,
double wx, double wy) {
GridBagConstraints cons = new GridBagConstraints();
cons.gridx = x;
cons.gridy = y;
cons.gridwidth = w;
cons.gridheight = h;
cons.weightx = wx;
cons.weighty = wy;
cons.fill = GridBagConstraints.BOTH;
panel.add(comp, cons);
}
}