How to create a partial border(with a hole)?

前端 未结 3 1921
挽巷
挽巷 2021-01-22 06:36

I wrote code in JavaFX and used CSS for setting styles for the above issue. The following code made borders for an AnchorPane that are 2 pixels wide:

    AnchorP         


        
3条回答
  •  再見小時候
    2021-01-22 07:03

    Use "nested backgrounds" to generate borders like this:

        pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
                + "-fx-background-insets: 0 0 0 0, 0 50 2 100, 2 2 2 2;");
    

    The JavaFX CSS documentation has all the details, but basically the way this works is that it creates three backgrounds, which are laid one over the other. The first is blue, with insets of 0 on every side. I.e.:

    pane.setStyle("-fx-background-color: blue; -fx-background-insets 0 0 0 0;");
    

    This creates a blue rectangle which fills the entire pane:

    The second background has the default root background from modena (-fx-background). It has insets of 0 at the top, 50 to the left, 2 at the bottom, and 100 at the right. So the first two nested backgrounds:

    pane.setStyle("-fx-background-color: blue, -fx-background;"
            + "-fx-background-insets: 0 0 0 0, 0 50 2 100;");
    

    produce this:

    Note the 2-pixel wide blue line at the bottom.

    Finally, the third background also has the default background color (-fx-background), and insets of two pixels on each side. So when this is laid over the previous two backgrounds, the desired effect is seen:

    When the values for all four sides are the same, you can replace the four values with a single value. So the CSS can be abbreviated

        pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
                + "-fx-background-insets: 0 , 0 50 2 100, 2;");
    

    Just a technical note: the default style sheet is not loaded unless at least one control is created, which is why I add a Label in the complete example below.

    Here is an SSCCE:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.AnchorPane;
    import javafx.stage.Stage;
    
    public class BorderWithGap extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            AnchorPane pane = new AnchorPane();
    
            Label label = new Label("Border with gap");
            AnchorPane.setTopAnchor(label, 50.0);
            AnchorPane.setLeftAnchor(label, 50.0);
            pane.getChildren().add(label);
    
            pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
                    + "-fx-background-insets: 0, 0 50 2 100, 2;");
    
    
            Scene scene = new Scene(pane, 600, 600);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题