How to create a Line using JavaFX?


A line is a geometrical structure that joins two points on an XY plane.

In JavaFX a line is represented by the javafx.scene.shape.Line class. This class contains four properties they are −

  • startX − This property represents the x coordinate of the starting point of the line, you can set the value to this property using the setStartX() method.

  • startY − This property represents y coordinate of the starting point of the line, you can set the value to this property using the setStartY() method.

  • endX − This property represents the x coordinate of the endpoint of the line, you can set the value to this property using the setEndX() method.

  • endY − This property represents y coordinate of the endpoint of the line, you can set the value to this property using the setEndY() method.

To create a circle you need to −

  • Instantiate this class.

  • Set the required properties using the setter methods or, bypassing them as arguments to the constructor.

  • Add the created node (shape) to the Group object.

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Line;
public class DrawingLine extends Application {
   public void start(Stage stage) {
      //Drawing a Line
      Line line1 = new Line();
      //Setting the properties of the circle
      line1.setStartX(200.0);
      line1.setStartY(50.0);
      line1.setEndX(200.0);
      line1.setEndY(250.0);
      //Setting other properties
      line1.setFill(Color.DARKCYAN);
      line1.setStrokeWidth(8.0);
      line1.setStroke(Color.DARKSLATEGREY);
      Line line2 = new Line();
      //Setting the properties of the circle
      line2.setStartX(75.0);
      line2.setStartY(150.0);
      line2.setEndX(450.0);
      line2.setEndY(150.0);
      //Setting other properties
      line2.setFill(Color.DARKCYAN);
      line2.setStrokeWidth(8.0);
      line2.setStroke(Color.BROWN);
      //Setting the Scene
      Group root = new Group(line1, line2);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Drawing a Line");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 14-Apr-2020

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements