如何使用 JavaFX 建立一個圓形?


圓是一條形成閉環的線,其上每一點到一箇中心點的距離都是確定的。圓由其圓心和半徑來定義,半徑指的是從圓心到圓上任意一點的距離。

在 JavaFX 中,圓由 javafx.scene.shape.Circle 類表示。此類包含三個屬性,即:

  • centerX – 此屬性表示圓形的中心點的 x 座標,您可以使用 setCenterX() 方法為該屬性設定值。

  • centerY – 此屬性表示圓形的中心點的 y 座標,您可以使用 setCenterY() 方法為該屬性設定值。

  • radius – 圓形的半徑,以畫素為單位,您可以使用 setRadius() 方法為該屬性設定值。

要建立圓形,您需要:

  • 例項化 Circle 類。

  • 使用設定方法設定必需的屬性,或將其作為建構函式的引數傳遞。

  • 將建立的節點(形狀)新增到 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.Circle;
public class DrawingCircle extends Application {
   public void start(Stage stage) {
      //Drawing a Circle
      Circle circle = new Circle();
      //Setting the properties of the circle
      circle.setCenterX(300.0f);
      circle.setCenterY(135.0f);
      circle.setRadius(100.0f);
      //Setting other properties
      circle.setFill(Color.DARKCYAN);
      circle.setStrokeWidth(8.0);
      circle.setStroke(Color.DARKSLATEGREY);
      //Setting the Scene
      Group root = new Group(circle);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Drawing a Circle");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:2020 年 4 月 14 日

729 次瀏覽

啟動你的 職業生涯

完成課程,獲得認證

開始
廣告