Javafx:填充线

Javafx: Padding line

我想在 javafx.scene.layout.VBox 中使用 class javafx.scene.shape.Line 的填充。 FXML(包含在另一个中):

<Tab xmlns:fx="http://javafx.com/fxml" fx:controller=...>
    <VBox>
        <Pane>...</Pane>
        <Line fx:id="line"/>
        ...
    </VBox>
</Tab>

我尝试使用 CSS 和 FXML 中的填充标记。我还尝试了 java 代码(在控制器 class 中):

@FXML MyLine spacerLine;
...
line.setStartX(5);
line.setEndX(scene.getWidth() - 5);

但是没有任何帮助。感谢您的帮助和阅读。

假设您要找的是水平尺之类的东西,我建议为此使用 Region,并使用 CSS 对其进行样式设置。

使用 Line 的问题在于,您要么使行 managed(这是默认设置),要么不受管理。如果它是托管的,则包含它的布局窗格将根据布局规则对其进行定位,因此您将无法指定 startX 等。如果不是托管的,则需要计算它的xy坐标;因此,例如在 VBox 中,您需要相对于 VBox 的其他子节点手动定位它。在任何一种情况下,您还需要根据容器的宽度计算 endX,容器的宽度可能随时更改(例如,如果用户调整 window 的大小)。

使用区域,你可以做到

<Region styleClass="hr" />

然后在外部 CSS 文件中应用适当的样式,例如:

.hr {
        -fx-background-color: slategray ;
        -fx-background-insets: 2 5 2 5 ;

        -fx-padding: 3 0 2 0  ;
}

这通过使用背景颜色(slategrey,但您当然可以选择任何您喜欢的颜色)来绘制规则,但使用插图在左右两侧留下 5 个未填充的像素,以及 2 个像素顶部和底部未填充的像素。填充确保该区域在顶部有 3 个像素(2 个未填充,1 个已填充),在底部有 2 个像素(未填充)。所以这最终得到一个填充区域一个像素高(看起来像一条水平线),在每一端拉伸整个宽度少 5 个像素。您可以尝试使用不同的插图和填充来获得不同的效果;例如如果需要,-fx-background-insets: 0 5 0 5;1 0 0 0 的填充将删除顶部和底部周围的 space。在所有边上使用 5 的插图,但 9 0 5 0 的填充将给出 4px 宽的线等。您也可以使用渐变填充...

这里有一个完整的 FXML 文件 (HRWithRegion.fxml) 来对此进行测试:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.Region?>

<VBox xmlns:fx="http://javafx.com/fxml/1">
    <VBox spacing="5">
        <Label text="Some content"/>
        <TextField />
        <Label text="Some more content"/>
    </VBox>
    <Region styleClass="hr" />
    <VBox>
        <Label text="Content below rule" />
    </VBox>
</VBox>

和一个 JavaFX 应用程序 class:只需将上面的 FXML 文件放在与此处源代码相同的文件夹中,并将 CSS 文件放在与 hr.css 相同的文件夹中文件夹。

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class HRTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("HRWithRegion.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("hr.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

这是结果(调整 window 大小后):