Remove padding/margin from JavaFX Label

SDS

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:

enter image description here

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();
    }
}
Sergey Grinev

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related