2

I am a beginner at Java and I have just recently started to take a look at GUI and JavaFX. And at the moment I am stuck trying to center a text inside a GridPane and would need som help with this, and an explaination to what I am doing wrong.

This is my code:

GridPane grid = new GridPane();
grid.setMinSize(100, 100);

Text text = new Text("Hello World!");
text.setTextAlignment(TextAlignment.CENTER);
grid.add(text, 0, 1);
grid.setStyle("-fx-background-color: #D8BFD8;");

This is not working (the text does not center), so I asume I am doing something wrong. But I cant understand what I am doing wrong?

Alex
  • 1,988
  • 3
  • 14
  • 20

1 Answers1

4

I would use Labels instead of Text, that way you can set the horizontal alignment:

Label label = new Label("Hello World!");
gridpane.add(label, 0, 1);
GridPane.setHalignment(label, HPos.CENTER);
Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • I cant get this to work aswell? I also get the warning that "setHalignment should be used in a static way" by eclipse. Why is that? :) – Alex Feb 20 '16 at 00:01
  • @JohanGudmundsson: Because you used `gridpane.setHalignment(label, HPos.CENTER)` instead of `GridPane.setHalignment(label, HPos.CENTER)` or for some reason named your `GridPane` variable `GridPane`. – fabian Feb 20 '16 at 00:37
  • Aah! I see! Okay so now I atleast dont get the warning message. But the text still does not center? "GridPane.setHalignment(label, HPos.CENTER);" – Alex Feb 20 '16 at 00:48
  • That will center the label in the specified cell in the grid pane. (BTW the same will work with a `Text`, you don't need a `Label`.) If it doesn't appear centered, it's probably because the grid pane is not centered in whatever container holds it. (It's also possible that the label is filling the cell, so it has extra space, and the text is not centered in the label.) Since you haven't posted a complete example, it's hard to really know... Also see http://stackoverflow.com/questions/35438104/javafx-alignment-of-label-in-gridpane/35438985#35438985 – James_D Feb 20 '16 at 01:21