โดยทั่วไป รูปร่าง 2 มิติคือรูปทรงเรขาคณิตที่สามารถวาดบนระนาบ XY ได้ ซึ่งได้แก่ เส้น สี่เหลี่ยมผืนผ้า วงกลม เป็นต้น
javafx.scene.shape แพ็คเกจให้คุณ คลาสต่างๆ แต่ละคลาสแสดงถึง/กำหนดออบเจกต์เรขาคณิต 2d หรือการดำเนินการกับพวกมัน คลาสที่ชื่อ Shape เป็นคลาสพื้นฐานของรูปร่าง 2 มิติทั้งหมดใน JavaFX
การสร้างรูปทรง 2 มิติ
ในการวาดรูปทรงเรขาคณิต 2 มิติโดยใช้ JavaFX คุณต้อง -
-
ยกตัวอย่างชั้นเรียน - ยกตัวอย่างคลาสที่เกี่ยวข้อง ตัวอย่างเช่น หากคุณต้องการวาดวงกลม คุณต้องสร้างตัวอย่างคลาส Circle ดังที่แสดงด้านล่าง −
//Drawing a Circle Circle circle = new Circle();
-
ตั้งค่าคุณสมบัติ − กำหนดคุณสมบัติของรูปร่างโดยใช้วิธีการของคลาสนั้น ๆ ตัวอย่างเช่น ในการวาดวงกลม คุณต้องมีจุดศูนย์กลางและรัศมี และคุณสามารถตั้งค่าได้โดยใช้เมธอด setCenterX(), setCenterY() และ setRadius() ตามลำดับ
//Setting the properties of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); circle.setRadius(100.0f);
-
เพิ่มวัตถุรูปร่างในกลุ่ม − สุดท้าย ส่งรูปร่างที่สร้างเป็นพารามิเตอร์ไปยังตัวสร้างกลุ่มเป็น −
Group root = new Group(circle);
ตัวอย่าง
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class CircleExample 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);
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing a Circle");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
} ผลลัพธ์
