可以设置 Rectangle 样式以显示边框吗?

Mus*_*ful 6 java javafx

以下应用:

public class Temp extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();

        Rectangle rect = new Rectangle(10.0,10.0);
        rect.setStyle("-fx-fill: red; -fx-border-style: solid; -fx-border-width: 5; -fx-border-color: black;");
        root.getChildren().add(rect);

        Scene scene = new Scene(root, 100, 100);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

产生以下窗口:

在此处输入图片说明

为什么我的矩形没有粗黑色边框?

Jam*_*s_D 7

否:Rectangle不支持-fx-border等:仅Region和子类支持。

所以试试

public class Temp extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();

        Region rect = new Region();
        rect.setStyle("-fx-background-color: red; -fx-border-style: solid; -fx-border-width: 5; -fx-border-color: black; -fx-min-width: 20; -fx-min-height:20; -fx-max-width:20; -fx-max-height: 20;");
        root.getChildren().add(rect);

        Scene scene = new Scene(root, 100, 100);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用“嵌套背景”来实现您的边框:

    rect.setStyle("-fx-background-color: black, red; -fx-background-insets: 0, 5; -fx-min-width: 20; -fx-min-height:20; -fx-max-width:20; -fx-max-height: 20;");
Run Code Online (Sandbox Code Playgroud)

你可以只用

    rect.setStyle("-fx-background-color: black, red; -fx-background-insets: 0, 5 5 0 0; -fx-min-width: 20; -fx-min-height:20; -fx-max-width:20; -fx-max-height: 20;");
Run Code Online (Sandbox Code Playgroud)


Tom*_*mas 5

试试这种风格:

rect.setStyle("-fx-fill: red; -fx-stroke: black; -fx-stroke-width: 5;");
Run Code Online (Sandbox Code Playgroud)

这一切都在JavaFX CSS 参考指南的第一部分。