Remove padding/margin from JavaFX Label

喜欢而已 提交于 2019-12-17 20:37:20

问题


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

回答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.




回答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);



回答3:


For more details see my post here Substructure styling

You could also do it like this after the stage.show().

With the example of an separator:

Separator separator = new Separator();
separator.setStyle(""
    + "-fx-border-width: 1px;"
    + "-fx-border-color: black;"
    + "-fx-padding: 0px;"
    + "");

stage.show()

Do

Node line = separator.lookup(".line");
line.setStyle(""
    + "-fx-border-insets: 0px;"
    + "-fx-border-width: 0px;"
    + "");

or this way index 0 because it has only one element at index 0 which is an Region with style calss .line

separator.getChildrenUnmodifiable().get(0).setStyle(""
    + "-fx-border-insets: 0px;"
    + "-fx-border-width: 0px;"
    + "");



回答4:


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.



来源:https://stackoverflow.com/questions/34359852/remove-padding-margin-from-javafx-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!