I have a GridPane
populated with ToggleButtons
. First row and column in that GridPane
holds Text
object labels.
I am unable to center the Text
objects with the ToggleButton
s so the text appears in the middle, using css.
(This answer shows how to achieve it by using GridPane.setHalignment(node, HPos.CENTER);
).
MCVE if needed :
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class GridTest extends Application {
private static final int COLS = 5, ROWS = 3;
@Override public void start(Stage stage) {
Scene scene = new Scene(makeGrid());
scene.getStylesheets().add(getClass().
getResource("GridTest.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
private Pane makeGrid() {
GridPane grid = new GridPane();
for(int rowIndex = 0; rowIndex < ROWS ; rowIndex++) {
Node[] nodes = new Node[COLS];
Node node;
for(int colIndex = 0; colIndex < COLS ; colIndex++) {
if (rowIndex == 0){ //col header;
String txt = (colIndex == 0) ?
" " : String.valueOf(colIndex);
node = new Text(txt);
}else if (colIndex == 0){//row header
node = new Text(String.valueOf(rowIndex));
}else {
node= new ToggleButton();
}
nodes[colIndex]= node;
}
grid.addRow(rowIndex, nodes);
}
return grid;
}
public static void main(String[] args) {
Application.launch(args);
}
}
CSS:
Text{
-fx-text-alignment: center;
}
GridPane {
-fx-hpos:center ;
-fx-hgap: 5;
-fx-vgap: 5;
-fx-padding:10;
}
ToggleButton {
-fx-pref-width:30;
}