Tommo
Tommo

Reputation: 987

FX - Suggestions for aligning CheckBox in Grid

Converting from Swing to FX here. We have some CheckBoxes where the Label appears on the left side of the CheckBox. We are accomplishing this by calling

setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);

The problem is that in some GridPanes, we'll have a Label in column 0 with a Node in column 1 on row 1, and then one of the CheckBoxes in the second row. Ideally the CheckBox and Node are aligned with each other. I am currently accomplishing this by setting the CheckBox's columnSpan to 2, and adding some right padding to align the fields. Is there an easier way to be doing this?

Our previous solution was to just separate the Label from the CheckBox, however this caused us to lose the functionality of selecting/deselecting the CheckBox upon clicking the label.

EDIT: enter image description here

I'm trying to figure out the best way to align the CheckBox with the Field.

Upvotes: 1

Views: 1766

Answers (1)

James_D
James_D

Reputation: 209358

I can't see a "nice" way to do what you want: the best I can come up with is to separate the label from the check box, and register a mouse listener with the label to toggle the state of the check box. Maybe someone else can see a more elegant way to do this.

SSCCE:

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class AlignedCheckBox extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane grid = new GridPane();
        Label checkboxLabel = new Label("Selected:");
        CheckBox checkBox = new CheckBox();
        checkboxLabel.setLabelFor(checkBox);

        checkboxLabel.setOnMouseClicked(e -> checkBox.setSelected(! checkBox.isSelected()));

        Label textFieldLabel = new Label("Enter text:");
        TextField textField = new TextField();

        grid.addRow(0, checkboxLabel, checkBox);
        grid.addRow(1, textFieldLabel, textField);

        ColumnConstraints leftCol = new ColumnConstraints();
        leftCol.setHalignment(HPos.RIGHT);
        leftCol.setHgrow(Priority.SOMETIMES);

        ColumnConstraints rightCol = new ColumnConstraints();
        rightCol.setHalignment(HPos.LEFT);
        rightCol.setHgrow(Priority.ALWAYS);

        grid.getColumnConstraints().addAll(leftCol, rightCol);

        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));

        Scene scene = new Scene(grid);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

enter image description here

Upvotes: 1

Related Questions