Reputation: 5496
I have a program that draws a chart with an axis with values. The values need to be drawn every 'y' pixels.
As shown in image, the black lines show where those values are drawn. A corresponding Label is drawn next to each axis value.
The problem is that with no displacement the origin is taken at the upper left corner of the label, so the text is not vertically aligned with the line.
In order to fix that I am thinking in getting the height of the label and manually offseting the y position for the label.
How can I get the height of the label in pixels?
This is the source code used to draw the lines and the labels:
public void drawAxis() {
int i = 0;
for(i=0; i<20; i++) {
long y_pos = 0;
y_pos = i*100;
Line gridTick = new Line(0, y_pos, 20, y_pos);
Label gridLabel = new Label(getStringFromValue(y_pos));
gridLabel.setTranslateX(30);
gridLabel.setTranslateY(y_pos);
rightAxisPanel.getChildren().add(gridTick);
rightAxisPanel.getChildren().add(gridLabel);
}
}
Upvotes: 0
Views: 258
Reputation: 82461
Just set make sure the label size is bigger than actually needed and the bounds are symetrical to the y coordinates of the line. Let Label
deal with the alignment.
Assuming the subclass of Parent
you extend does not modify the layout position, you can do
public void drawAxis() {
int i = 0;
for(i=0; i<20; i++) {
double y_pos = i*100;
Line gridTick = new Line(0, y_pos, 20, y_pos);
Label gridLabel = new Label(getStringFromValue(y_pos));
gridLabel.setLayoutX(30);
// make sure label bounds range from y_pos-25 to y_pos+25 vertically
gridLabel.setLayoutY(y_pos-25);
gridLabel.setPrefHeight(2*25);
gridLabel.setMinHeight(Region.USE_PREF_SIZE);
// set text alignment in label area
gridLabel.setAlignment(Pos.CENTER_LEFT);
rightAxisPanel.getChildren().addAll(gridTick, gridLabel);
}
}
This assumes that you do not use font sizes that require more than 50 pixels to display vertically.
Upvotes: 1