Search code examples
javafxlinescene

how to add vertical lines inside the line


Here is my code as follows:

    public void start(Stage primaryStage) throws Exception {
    Pane root = new Pane();
    Scene scene = new Scene(root, 500, 500);

    Line line = new Line(100,0,300,0);
    line.setStrokeWidth(20);
    line.setStroke(Color.YELLOW);
    root.getChildren().add(line);

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

Here is the image (as it will be more clear if I show the image)

Line

My question is that: I want to design my line, so I want to add vertical lines inside my line. Is there any way I can do that? Any help is appreciated!


Solution

  • It can be drawn for example by using two Lines:

    public class LineDemo extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            Pane root = new Pane();
            Scene scene = new Scene(root, 500, 500);
    
            // Background line
            Line lineBlack = new Line(98,50,302,50);
            lineBlack.setStroke(Color.BLACK);
            lineBlack.setStrokeWidth(24);
            lineBlack.setStrokeLineCap(StrokeLineCap.BUTT);
    
            // Top line
            Line line = new Line(100,50,300,50);
            line.setStroke(Color.YELLOW);
            line.setStrokeWidth(20);
    
            // Vertical lines
            line.getStrokeDashArray().addAll(20d, 2d, 40d, 2d, 82d, 2d, 20d, 2d, 30d);
            line.setStrokeLineCap(StrokeLineCap.BUTT);
    
    
            root.getChildren().addAll(lineBlack, line);
    
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    To get a result like:

    enter image description here

    Note: It can be also solved completely with LinearGradients.