Search code examples
javaswinggridbaglayout

Why do they declare these static variables in this Java GridBagLayoutDemo example?


I'm studying Java GUI & how GridBagLayout works:

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 ) I'm confused as to why you need/want the 3 booleans here - shouldFill , shouldWeightX , and RIGHT_TO_LEFT - i.e can't we simply remove those 3 if-statements ?


Solution

  • It is not required, but sometimes declaring constants helps to have an overview of all the set values. This allows you to quickly try out value combinations without searching in the code (so it is more abstract). Maybe the programmer chose to only have booleans to align/simplify the values... NOTE: constants should respect the syntax used by RIGHT_TO_LEFT.