Remove padding/margin from JavaFX Label
One of the more dynamic ways to do this is to use a Text
instead of a Label and set the boundsType
as VISUAL
. This results in a Text without any padding on the any of the sides of the Text, irrespective of the font size.
Text text = new Text();
text.setBoundsType(TextBoundsType.VISUAL);
You can achieve that by adding -fx-padding: -10 0 0 0;
to the list of your styles.
For more flexible solution you can use FontMetrics
information:
FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(label.getFont());
label.setPadding(new Insets(-metrics.getDescent(), 0, 0, 0));
NB: You need to call that code after scene.show()
. Before that graphics engine is not ready to provide correct metrics.
For me it was easiest to just use setPadding.
label.setPadding(new Insets(-2,0,0,0)); //top, right, bottom, left
This way I did not have to deal with the css-style sheet.