JavaFX如何在GridPane中的HBox中垂直对齐CheckBox

时间:2016-09-22 21:31:30

标签: java javafx java-8 javafx-8

首先,生成说明问题的UI的代码:

package test;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(final Stage window) throws Exception {
        // Create a VBox to hold the table and button
        final GridPane root = new GridPane();
        root.setHgap(5);
        root.setVgap(5);

        // Add a combo-box to the first row
        final ComboBox<String> dropdown1 = new ComboBox<>();
        dropdown1.getItems().add("Option 1");
        dropdown1.getSelectionModel().selectFirst();
        root.add(dropdown1, 0, 0);

        // Add a checkbox to the first row
        final CheckBox checkbox1 = new CheckBox("CB Text 1");
        root.add(checkbox1, 1, 0);

        // Add a combo-box to the second row
        final ComboBox<String> dropdown2 = new ComboBox<>();
        dropdown2.getItems().add("Option 2");
        dropdown2.getSelectionModel().selectFirst();
        root.add(dropdown2, 0, 1);

        // Add a checkbox, wrapped in an HBox, to the second row
        final CheckBox checkbox2 = new CheckBox("CB Text 2");
        final HBox hbox = new HBox(checkbox2);
        hbox.setAlignment(Pos.BASELINE_LEFT);
        root.add(hbox, 1, 1);
        GridPane.setValignment(hbox, VPos.BASELINE);

        // Show the JavaFX window
        final Scene scene = new Scene(root);
        window.setScene(scene);
        window.show();
    }
}

以上代码生成以下UI(Java 8u102 Windows x64):

Example Application

如图所示,第二行CheckBox的垂直对齐方式与ComboBox未对齐。我希望一切都在文本基线上对齐。如何在GridPane中获取第二行以匹配第一行的对齐方式,而不删除HBox

1 个答案:

答案 0 :(得分:3)

将填充有问题的单元格的代码修改为以下内容:

// Add a checkbox, wrapped in an HBox, to the second row
final CheckBox checkbox2 = new CheckBox("CB Text 2");
final HBox hbox = new HBox(checkbox2);
hbox.setFillHeight(true);          // Added this
hbox.setAlignment(Pos.CENTER_LEFT);// Changed the alignment to center-left
root.add(hbox, 1, 1);
//GridPane.setValignment(hbox, VPos.BASELINE); This is unnecessary

此代码将强制HBox与行的高度相同,然后将CheckBox垂直居中于其中。