Remove padding/margin from JavaFX Label
Solution 1
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.
Solution 2
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);
Solution 3
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.
SDS
Software Engineer working on Java, SWT and JavaFX applications.
Updated on July 29, 2022Comments
-
SDS almost 2 years
Is there a way to remove the default space (padding/margin) that JavaFX label adds? I want to get rid of the space displayed between the black lines on the image below:
Source code:
public class LabelTest extends Application { @Override public void start(final Stage primaryStage) { final Group root = new Group(); final Scene scene = new Scene(root, 300, 130, Color.WHITE); final GridPane gridpane = new GridPane(); gridpane.setPadding(new Insets(5)); gridpane.setHgap(10); gridpane.setVgap(10); final Label label = new Label("Label"); label.setStyle("-fx-font-size:44px;-fx-font-weight: bold;-fx-text-fill:#5E34B1;-fx-background-color:#ffc300;"); GridPane.setHalignment(label, HPos.CENTER); gridpane.add(label, 0, 0); root.getChildren().add(gridpane); primaryStage.setScene(scene); primaryStage.show(); } }
-
SDS over 8 yearsIs there a dynamic approach than hardcoding a value? I don't want to hardcode (-10 in your example) a value and later see that the actual text gets chopped off
-
SDS over 8 yearsis there any other control that I can use which doesn't add the padding by default but just the text?
-
Tharindu Sathischandra almost 4 yearsCan't we set it using CSS?