开发者

Should I make one GridBagConstraint object for each component

As the title says, should I make one GridBagConstraint object for each component? In

java how to program 8th edition

they make a method named addComponent, however when I read about GridBagLayout I always end up rea开发者_运维技巧ding that I should not use the same constraint-object. What should I follow?

Thank you.


It's perfectly safe to reuse the same GridBagConstraint instance for each component added with add. The Sun GridBagLayout example reuses the same GridBagConstraint instance. Just be aware all GridBagConstraint fields will be used, thus you may need to reset some of them.


Taking a look at GridBagLayout's method calls that are called while adding any given component, the final call goes to:

public void setConstraints(Component comp, GridBagConstraints constraints) {
    comptable.put(comp, (GridBagConstraints)constraints.clone());
}

Here, the GridBagLayout is creating a clone of the constraints object passed in which means that each component being added has a fresh copy of the GridBagConstraints. So, it should be perfectly fine to reuse the GridBagConstraints object and making changes to it as necessary.

Regards

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜