swing为什么在这个Java GridBagLayoutDemo示例中声明这些静态变量?
我在学习JavaGUI&;{a1}的工作原理:
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;
}
(fullsource here)我很困惑,为什么你需要/想要这里的3个布尔值——shouldFill、shouldwertx和RIGHT_to_LEFT——也就是说,我们不能简单地删除这3个if语句吗
# 1 楼答案
这不是必需的,但有时声明常量有助于全面了解所有设置值。这允许您快速尝试值组合,而无需在代码中搜索(因此更抽象)。也许程序员选择只使用布尔值来对齐/简化值。。。 注意:常量应该遵守从右到左使用的语法