How does GridBagLayout functions such as gridwidth/height and gridx/y work to scale the size of the GUI?

て烟熏妆下的殇ゞ 提交于 2019-12-24 14:25:20

问题


I was recently introduced to GridBagLayout to substitute the vanilla JPanel layout, but I am having trouble working with the functions like gridwidth/height and gridx/y. I am not sure how they work exactly in changing the size of the GUI and the positions of the buttons. Below is a code my professor gave me to use for reference, and I tried fiddling with certain numbers but the results never turned out to be what I expected to happen, and I am not sure why.

EDIT 1: To clarify, I am wondering exactly how do the gridwidth, gridheight, gridx, and gridy functions work to resize the GUI and position the Buttons' locations.

import java.awt.*;
import javax.swing.*;

class Bar1 {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        c.gridx=0;
        c.gridy=0;
        c.gridwidth=2;
        c.gridheight=1;
        c.weightx = 2;
        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        JButton b = new JButton("Hello");
        panel.add(b, c);
        c.gridx=0;
        c.gridy=1;
        c.gridwidth=1;
        c.gridheight=1;
        JButton b2 = new JButton("World");
        panel.add(b2, c);
        c.gridx=1;
        c.gridy=1;
        c.gridwidth=1;
        c.gridheight=1;
        JButton b3 = new JButton("!!!");
        panel.add(b3, c);

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

    }
}

来源:https://stackoverflow.com/questions/29811091/how-does-gridbaglayout-functions-such-as-gridwidth-height-and-gridx-y-work-to-sc

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