JavaFX: draw sharp thin lines

I am wondering how to draw sharp thin lines using JavaFX. I would like my lines to be black and 1 pixel high. Here is what I have at the moment:

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            root.setSnapToPixel(true);
            Scene scene = new Scene(root,400,400);

            Line line = new Line();
            Line line2 = new Line();

            line.setStartX(0.0f);
            line.setEndX(100f);
            line.setStartY(30f);
            line.setEndY(30f);
            line.setStrokeWidth(1f);
            line.setStrokeType(StrokeType.OUTSIDE);
            line.setStroke(Color.BLACK);

            line2.setStartX(50.0f);
            line2.setEndX(200f);
            line2.setStartY(100f);
            line2.setEndY(100f);
            line2.setStrokeWidth(1f);
            line2.setStrokeType(StrokeType.OUTSIDE);
            line2.setStroke(Color.BLACK);

            root.getChildren().addAll(line, line2);

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Here is what I get:

result

The lines are quite thick, and calling the method setStrokeWidth()with a value of <1 does not affect the height, and the black color disappears. Any idea how to get 1 pixel high line?

I can achieve this using rectangles with a height of 1 pixel, but it seems a bit dirty.

+4
source share
1 answer

If you use StrokeType.CENTEREDand start the x / y values ​​at half unit, then the lines turn out to be hair lines to me.

public void start(Stage primaryStage) {
    try {
        BorderPane root = new BorderPane();
        root.setSnapToPixel(true);
        Scene scene = new Scene(root, 400, 400);

        Line line = new Line();
        Line line2 = new Line();

        line.setStartX(0.5);
        line.setEndX(100.5);
        line.setStartY(30.5);
        line.setEndY(30.5);
        line.setStrokeWidth(1.0);
        line.setStrokeType(StrokeType.CENTERED);
        line.setStroke(Color.BLACK);

        line2.setStartX(50.5);
        line2.setEndX(200.5);
        line2.setStartY(100.5);
        line2.setEndY(100.5);
        line2.setStrokeWidth(1.0);
        line2.setStrokeType(StrokeType.CENTERED);
        line2.setStroke(Color.BLACK);

        root.getChildren().addAll(line, line2);

        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

, JavaFX , location + 0.5 .

0

Source: https://habr.com/ru/post/1607543/


All Articles