Specify Grid Parameter of GridBagLayout Without Component

半腔热情 提交于 2019-12-11 02:48:28

问题


I was attempting to help another user, and I came across a problem where I was wanting to do this with GridBagLayout:

        c1   |                  c2                     |   c3
       ~10%  |                 ~80%                    |  ~10%
             v                                         v   
     |-------------------------------------------------|
 r1  |                       B1                        |  <S1>
~50% |-------------------------------------------------|
---->
             |--------------------------------------------------|
 r2    <S2>  |                      B2                          |
~50%         |--------------------------------------------------|

The specific problem is that I want to set the weight of c2 to be 80%, but I do not have a component that exists within c2 exclusively (setting the weight of B1 or B2 will not yield the desired effect as they also exist in c1 and c3, respectively).

Is there a way to specify grid constraints without either adding an invisible component or subdividing the panel? After looking at the Javadoc, I'm guessing not, but I figured I'd post the question anyway for posterity.

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);
  }
}

来源:https://stackoverflow.com/questions/45198804/specify-grid-parameter-of-gridbaglayout-without-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!