繁体   English   中英

用于构建GUI面板的Java函数

[英]Java function for building GUI panel

我正在使用网格包为我的应用程序构建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);
    }

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

我只是想做些什么还是我的代码中缺少某些东西? 有什么建议么?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM