Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Rectangle be styled to show a border?

Tags:

java

javafx

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:

enter image description here

Why doesn't my rectangle have thick black borders?

like image 324
Museful Avatar asked Oct 30 '15 11:10

Museful


2 Answers

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;");
like image 65
James_D Avatar answered Oct 02 '22 13:10

James_D


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.

like image 38
Tomas Avatar answered Oct 02 '22 13:10

Tomas