【问题标题】:Java function for building GUI panel用于构建 GUI 面板的 Java 函数
【发布时间】:2016-06-30 05:27:50
【问题描述】:

我正在使用网格包为我的应用程序构建一个 GUI 布局,并且我试图想出一个函数来布局每个元素,这样我就不必重复输入相同的网格包代码了超过。我想重写这段代码:

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

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

我正在尝试做的事情是可能的还是我在代码中遗漏了什么?有什么建议吗?

【问题讨论】:

    标签: java swing layout-manager gridbaglayout


    【解决方案1】:

    每次调用方法时,您都会创建一个新的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。

    【讨论】:

    • 我明白了。我将 GridBagLayout() 调用保留在调用 labelPosition() 函数的函数中,并且仅将 Constraints() 调用移动到新函数。我很高兴这成功了。这从该文件中删除了大约 100 行代码,并使其更具可读性。感谢安德烈亚斯。
    猜你喜欢
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2011-03-12
    • 2013-12-23
    • 2011-04-20
    • 2010-09-25
    相关资源
    最近更新 更多