Reputation: 4677
First, code that generates a UI that illustrates the problem:
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();
}
}
The above code generates the following UI (Java 8u102 Windows x64):
As shown in the image, the vertical alignment of the CheckBox
in the second row is misaligned with the ComboBox
. I expect everything to be aligned on the text baseline. How can I get the second row in the GridPane
to match the alignment of the first row, without removing the HBox
?
Upvotes: 2
Views: 6165
Reputation: 10859
Modify the code that populates the offending cell to be the following:
// 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
This code will force the HBox
to be the same height as the row, then vertically center the CheckBox
within it.
Upvotes: 5