JavaFX Line

0

JavaFX Line Tutorial:

  • The lines are derived class of the shape class.
  • To render graphics we use basic Shapes like Lines, circles and rectangles etc.
  • In JavaFX lines are generated(rendered) using screen coordinate System As (x,y).
  • The Screen coordinate system start from (0,0) at top left corner.
  • And x coordinate increase as point moving left to right. But y increase top to bottom.

Constructor :

  • Line()It creates an empty instance of Line.
  • Line(double startX, double startY, double endX, double endY)It creates a new instance of Line.

Drawing a new line:

First create an empty line object

Line line = new Line();
Then add starting an ending point as

line.setStartX(0.0f);
line.setStartY(0.0f);
line.setEndX(100.0f);
line.setEndY(100.0f);

Another method for creating a Line:

Line line = new Line(100,40,50,150);
It Draw a line with start point (100,50) and end point is (40,150).

Example of line:


package javafxtuts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

/**
 *
 * @author JavaFXtuts.com
 */
public class Javafxtuts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
         Pane root = new Pane();
        //creating first line 
        Line line = new Line(50,40,230,40);
        
        //creating second line using empty constructor 
        Line line1=new Line();
        line1.setStartX(10);
        line1.setStartY(50);
        line1.setEndX(120);
        line1.setEndY(200);
        
        root.getChildren().addAll(line,line1);

        Scene scene = new Scene(root, 250, 220);
        
        primaryStage.setTitle("javafxtuts.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output:

Explaination :
  • First we draw a line as
    Line line = new Line(50,40,230,40);
    It create a line that goes from (50,40) to (230,40).
  • Then we draw a line using empty constructor as
    Line line1=new Line();
    And the set X and Y coordinates using setter methods.
  • And finally add both lines to the Pane Layout.
Share.

Leave A Reply