0

我正在研究 Java GUI 以及GridBagLayout 的工作原理:

final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane) {
    if (RIGHT_TO_LEFT) {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill) {
    //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
    }

    button = new JButton("Button 1");
    if (shouldWeightX) {
        c.weightx = 0.5;
}

(完整来源在这里)我很困惑为什么你需要/想要这里的 3 个布尔值 - shouldFill、shouldWeightX 和 RIGHT_TO_LEFT - 即我们不能简单地删除这 3 个 if 语句吗?

4

1 回答 1

2

这不是必需的,但有时声明常量有助于了解所有设置值。这使您无需在代码中搜索即可快速尝试值组合(因此更抽象)。也许程序员选择只使用布尔值来对齐/简化值......注意:常量应该尊重 RIGHT_TO_LEFT 使用的语法。

于 2012-11-21T15:59:02.603 回答