简体   繁体   中英

Can a Rectangle be styled to show a border?

The following application:

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

produces the following window:

在此输入图像描述

Why doesn't my rectangle have thick black borders?

No: Rectangle does not support -fx-border etc: only Region and subclasses do.

So try

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

Alternatively, you can implement your border using "nested backgrounds":

    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;");

And you can add borders to some sides only with

    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;");

Try this style instead:

rect.setStyle("-fx-fill: red; -fx-stroke: black; -fx-stroke-width: 5;");

This is all in the first section of the JavaFX CSS Reference Guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM