How can i remove the space inside a Separator?

2019-08-17 06:53发布

问题:

I have created a Horizontal Separator in a VBox.

Following is the code:

Separator s = new Separator(Orientation.HORIZONTAL);
s.setStyle(""
    + "-fx-border-width: 1px;"
    + "-fx-border-color: black;"
    + "-fx-padding: 0px;"
    + "");
getChildren().add(s);

I want to remove the space inside the Separator. So I set the CSS property -fx-padding: 0px; but it doesn't seem to work.

How can I do it??!!


Here is the image Separator

回答1:

The separator consists out of two Elements.

The Separator root node with css class separator and an child element Region with css class line

If you want to remove the line in the middle of the black box than you have to modify the region(line) child and set its border insets and width to 0px

for example:

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

stage.show()

And than after stage.show() you will have access to its childern via lookup or getChildrenUnmodifiable()

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

or

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

and third the option of With metrics

FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(label.getFont());
label.setPadding(new Insets(-metrics.getDescent(), 0, 0, 0));

and fourth option of With Bounds which is not applyable for all Nodes and does not work in this case.

Text text = new Text();
text.setBoundsType(TextBoundsType.VISUAL);

And as last option you could add an CSS file which changes the style of the .line class

App.css:

.line {
    -fx-border-width: 0px;
    -fx-border-insets: 0px;
}

.separator {
    -fx-padding: 0px;
    -fx-border-insets: 0px;
    -fx-border-width: 1px;
    -fx-border-color: black;
}

And than you just have to apply this css to your scene.

scene.getStylesheets().add("App.css");

If you dont know about it already maybe you should checkout Scenic View which is a good tool if you want to inspect JavaFx applications.