如何使用 JavaFX 建立一條線段?


線段是連線在 XY 平面上的兩點的幾何結構。

在 JavaFX 中,線段由 javafx.scene.shape.Line 類表示。該類包含四個屬性,它們是:-

  • startX − 此屬性表示線段起點的 x 座標,你可以使用 setStartX() 方法為其設定值。

  • startY − 此屬性表示線段起點的 y 座標,你可以使用 setStartY() 方法為其設定值。

  • endX − 此屬性表示線段終點的 x 座標,你可以使用 setEndX() 方法為其設定值。

  • endY − 此屬性表示線段終點的 y 座標,你可以使用 setEndY() 方法為其設定值。

若要建立圓形,你需要:-

  • 例項化該類。

  • 使用 setter 方法或將 setter 方法作為建構函式的引數來設定必需的屬性。

  • 將建立的節點(形狀)新增到 Group 物件。

示例

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);
   }
}

輸出

更新於:14-Apr-2020

171 次瀏覽

開啟您的職業生涯

透過完成課程,獲得認證

開始
廣告
© . All rights reserved.