我正在学习 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;
}
( full source here ) 我很困惑为什么你需要/想要这里的 3 个 boolean 值 - shouldFill 、 shouldWeightX 和 RIGHT_TO_LEFT - 即我们不能简单地删除这 3 个 if 语句吗?
最佳答案
这不是必需的,但有时声明常量有助于了解所有设置值。这使您可以快速尝试值组合,而无需在代码中搜索(因此更抽象)。也许程序员选择只使用 boolean 值来对齐/简化值...... 注意:常量应遵循 RIGHT_TO_LEFT 使用的语法。
关于java - 为什么他们在这个 Java GridBagLayoutDemo 示例中声明这些静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497034/