我正在使用网格包为我的应用程序构建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);
}
现在它编译,但是当我运行它时,它不起作用。所有标签都显示在一行而不是我正在寻找的布局中。
我正在尝试做的只是可能,还是我在代码中遗漏了什么?有什么建议吗?
答案 0 :(得分:2)
每次调用方法时,您都会创建一个新的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。