Java 用于构建 GUI 面板的函数

Java function for building GUI panel

我正在使用 grid bag 为我的应用程序构建 GUI 布局,我正在尝试想出一个函数来布局每个元素,这样我就不必不断地重新输入相同的 grid bag 代码一遍又一遍。我想重写这段代码:

GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints bc = new GridBagConstraints();
this.setLayout(gridbag);

bc.fill = GridBagConstraints.HORIZONTAL;
bc.anchor = GridBagConstraints.WEST;
bc.insets = new Insets(0, 10, 10, 0);
bc.gridx = 0;
bc.gridy = 0;
bc.gridwidth = 1;
this.add(programNameLabel, bc);

这样就可以编写调用这样的函数:

labelPosition(GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 0, 10, 10, 0, 0, 0, 1, programNameLabel);

这是我为任务编写的函数。

protected void labelPosition(int axis, int direction, int insetOne, int insetTwo, int insetThree, int insetFour, int gridX, int gridY, int gridWidth, JLabel name)
    {
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints bc = new GridBagConstraints();
        this.setLayout(gridbag);

        bc.fill = axis;
        bc.anchor = direction;
        bc.insets = new Insets(insetOne, insetTwo, insetThree, insetFour);
        bc.gridx = gridX;
        bc.gridy = gridY;
        bc.gridwidth = gridWidth;
        this.add(name, bc);
    }

现在它编译了,但是当我运行它时,它不起作用。所有标签都显示在一行中,而不是我正在寻找的布局。

我想做的事情是简单可行的还是我的代码中遗漏了什么??有什么建议吗?

每次调用您的方法时,您都在创建一个新的 GridBagLayout()。你应该只这样做一次,并且在你的方法中只创建 GridBagConstraints 并将新标签添加到你的容器中(顺便说一句,通过使用像 JComponent 这样的更通用的类型,你可以重用相同的方法即使对于 JLabel 以外的其他组件):

protected void addComponent(int axis, int direction, int insetOne, int insetTwo, int insetThree, int insetFour, 
                            int gridX, int gridY, int gridWidth, JComponent component) {

    GridBagConstraints bc = new GridBagConstraints();

    bc.fill = axis;
    bc.anchor = direction;
    bc.insets = new Insets(insetOne, insetTwo, insetThree, insetFour);
    bc.gridx = gridX;
    bc.gridy = gridY;
    bc.gridwidth = gridWidth;

    this.add(component, bc);
}

...
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);

addComponent(GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 0, 10, 10, 0, 0, 0, 1, new JLabel("Hello"));
addComponent(GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 0, 10, 10, 0, 0, 1, 1, new JButton("World"));
...

附带说明一下,如果这是一个新项目,您可以考虑查看 JavaFX 而不是 Swing。