Reputation: 3
Right now I'm trying to code a simple abacus with JavaFX. There are balls on horizontal rails arranged in a gridpane, and they move on mouseClick from side to side. I'm trying to add labels to each ball from 10-1, but it seems that by simply adding the circles into a gridpane they don't get a CenterX/Y assigned. Since that's how I'm trying to position my text it doesn't show up at all. The relevant part of my code is:
// Stack Gridpane into root pane to organize circles on rails
GridPane grid = new GridPane();
// loop to instantiate all circles in a 5x10 grid, add to gridpane
for (int row = 0; row < 5; row++) {
for (int count = 10; count > 0; count--) {
Circle circle = new Circle() ;
circle.setRadius(20);
grid.add(circle,count,row);
// generate Labels and position on circle
Text label = new Text(Integer.toString(count));
label.getStyleClass().add("text");
label.setX(circle.getCenterX());
label.setY(circle.getCenterY());
//bind label to circle movement
label.translateXProperty().bind(circle.translateXProperty());
root.getChildren().add(label);
}
}
root.getChildren().add(grid);
When I add a System.out.println(label) I can see that the labels get generated properly, but the coordinates always stay at 0/0. The circles themselves get arranged in a grid the way they are supposed to though. Any help would be greatly appreciated!
Upvotes: 0
Views: 219
Reputation: 8363
There are some problems here that I see.
Firstly, setX()
and setY()
do not work when the node is inside some kind of Pane
subclass that manages layout for you. This is because the layout manager will override this value when it's trying to layout its children.
Secondly, you are adding the label to root node, which is going to make all the Text
gather at the same place.
This is what I would do, using StackPane
, which allows you to stack multiple nodes at the same place. Furthermore, it automatically centers all its children.
// Stack Gridpane into root pane to organize circles on rails
GridPane grid = new GridPane();
// loop to instantiate all circles in a 5x10 grid, add to gridpane
for (int row = 0; row < 5; row++) {
for (int count = 10; count > 0; count--) {
StackPane sp = new StackPane();
grid.add(sp, count, row);
Circle circle = new Circle();
circle.setRadius(20);
// generate Labels and position on circle
Text label = new Text(Integer.toString(count));
label.getStyleClass().add("text");
label.setFill(Color.RED); // Added so it's visible
// Don't need these
//label.setX(circle.getCenterX());
//label.setY(circle.getCenterY());
//bind label to circle movement
//label.translateXProperty().bind(circle.translateXProperty());
//root.getChildren().add(label);
// Add circle and label to StackPane so it'll handle layout for you
sp.getChildren().addAll(circle, label);
}
}
root.getChildren().add(grid);
From what I see, you do have some translation intended. That would be a little tricky to do, depending on what exactly you need.
Upvotes: 1