在尝试使一些Swing代码更具可读性时,我创建了一个InlineGridBagConstraints
类,如下所示:
public class InlineGridBagConstraints extends GridBagConstraints {
public InlineGridBagConstraints gridx(int x) {
gridx = x;
return this;
}
public InlineGridBagConstraints gridy(int y) {
gridy = y;
return this;
}
public InlineGridBagConstraints gridheight(int h) {
gridheight = h;
return this;
}
public InlineGridBagConstraints gridwidth(int w) {
gridwidth = w;
return this;
}
// .... and so on, for all fields.
}
目的是改变这种代码:
GridBagConstraints c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 3;
myJPanel.add(myJButton, c);
c.gridx = 3;
c.gridwidth = 2;
myJPanel.add(myOtherJButton, c);
c.gridx = 1;
c.gridy = 5;
c.gridheight = 4;
myJPanel.add(yetAnotherJButton, c);
......更容易理解和阅读,比如:
InlineGridBagConstraints c = new InlineGridBagConstraints();
myJPanel.add(myJButton, c.gridx(2).gridy(1).gridwidth(3));
myJPanel.add(myOtherJButton, c.gridx(3).gridy(1).gridwidth(2);
myJPanel.add(yetAnotherJButton, c.gridx(1).gridy(5).gridheight(4);
但是,上面的代码无效。当我尝试它时,所有组件占据JPanel
中心的相同区域并相互重叠。它们没有在GridBagLayout
中间隔开。但是,如果我将uglier版本与常规GridBagConstraints
一起使用,则它可以完全按预期工作。
我已经尝试将InlineGridBagConstraints
强制转换为GridBagConstraints
,认为这可能是一个问题(尽管不应该这样),但这根本没有帮助。
我已经没想完了。有谁知道为什么会发生这种情况,或者第一个(标准)和第二个(内联)实现之间的关键区别是什么?
答案 0 :(得分:2)
至于我可以依赖你写的东西,这应该有效。因此,我建议您开始在代码中查找其他错误。
您是否在两个示例中正确设置了LayoutManager?
更新:尝试摆脱构造函数中的重置调用。超类构造函数将正确地完成工作。
答案 1 :(得分:2)
我真的不知道你的GUIConstants
定义了什么,因为我们没有看到它,但是将InlineGridBagConstraints
中的reset()方法更改为下面的方法,使得你的UI看起来很像预期:
public InlineGridBagConstraints reset() {
gridx = 0;
gridy = 0;
gridheight = 1;
gridwidth = 1;
insets = new Insets(5, 5, 5, 5);
fill = GridBagConstraints.BOTH;
anchor = GridBagConstraints.CENTER;
return this;
}