我试图帮助另一个用户,但遇到了一个问题,我想用 GridBagLayout 来做到这一点:
c1 | c2 | c3
~10% | ~80% | ~10%
v v
|-------------------------------------------------|
r1 | B1 | <S1>
~50% |-------------------------------------------------|
---->
|--------------------------------------------------|
r2 <S2> | B2 |
~50% |--------------------------------------------------|
具体问题是我想将c2的权重设置为80%,但是我没有c2中存在的组件只(设置B1或B2的权重不会产生预期的效果,因为它们也分别存在于c1和c3中)。
有没有办法指定网格约束without要么添加一个不可见的组件,要么细分面板?看完之后Javadoc https://docs.oracle.com/javase/7/docs/api/java/awt/GridBagLayout.html,我猜不是,但我想无论如何我都会为后代发布这个问题。
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);
}
}