Starting GridBagLayout from top left corner in Java Swing

后端 未结 6 732
执念已碎
执念已碎 2021-02-13 18:39

I\'m new to Java Swing and I have been struggling to start the GridBagLayout from top left corner so that c.gridx=0 c.gridy=0 will put my object on the top left corner.

6条回答
  •  天命终不由人
    2021-02-13 19:12

    You need to use your GridBagConstraints' anchor property. This should do it for you:

    frame.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;
    frame.add(panel, gbc);
    

    I'm not guaranteeing that you won't have to set other properties of the constraints object to get the layout you desire. In particular, you may need to set weightx and weighty to be 1 so that the panel takes up all of the available space given to it.

提交回复
热议问题