我正在研究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;
}


(完整的source here)我对您为什么需要/想要这里的3个布尔值感到困惑-shouldFill,shouldWeightX和RIGHT_TO_LEFT-即我们不能简单地删除这3个if语句吗?

最佳答案

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

关于java - 为什么它们在此Java GridBagLayoutDemo示例中声明这些静态变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13497034/

10-12 14:24
查看更多