Skip to content
Advertisement

Why are my JavaFX buttons unevenly spaced?

I’m new to JavaFX, trying to build a GUI program that displays a bill for a table at a restaurant when you click on that table. The spacing is off between the table buttons and I’m not sure why.

enter image description here

The GUI class for my program:

package restaurantBillingProgram;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.geometry.Pos;

public class BillingGUI extends Application {

    @Override
    public void start(Stage primaryStage) {

        // Create grid pane
        GridPane pane = new GridPane();
        pane.setAlignment(Pos.CENTER);
        pane.setHgap(5);
        pane.setVgap(5);

        // Label
        pane.add(new Label("Generate bill"), 1, 0);

        // Buttons
        Button btT1 = new Button("Table 1");
        pane.add(btT1, 0, 1);
        btT1.setOnAction(e - > Billing.generateT1());

        Button btT2 = new Button("Table 2");
        pane.add(btT2, 1, 1);
        btT2.setOnAction(e - > Billing.generateT2());

        Button btT3 = new Button("Table 3");
        pane.add(btT3, 2, 1);
        btT3.setOnAction(e - > Billing.generateT3());

        // Create scene and place in stage
        Scene scene = new Scene(pane, 250, 250);
        primaryStage.setTitle("Restaurant Billing Program");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // Main method
    public static void main(String[] args) {
        launch(args);
    }
    }

Advertisement

Answer

From the Javadoc:

  • Row/Column Sizing

    By default, rows and columns will be sized to fit their content; a column will be wide enough to accommodate the widest child, …

The label in row 0 column 1 forces that column to be wider.

You probably want the label to be centered and span all 3 columns.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement