Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธาสร้าง Rectangle ใน JavaFX

Rectangle เป็นรูปปิด 4 ด้าน มุมระหว่างด้านใดด้านหนึ่งเป็นมุมฉาก และด้านตรงข้ามขนานกัน กำหนดโดยความสูงและความกว้าง

ใน JavaFX Rectangle แทนด้วยคลาส javafx.scene.shape.Rectangle คลาสนี้มี 4 คุณสมบัติ:

  • height - ความสูง ตั้งค่าด้วย setHeight()
  • width - ความกว้าง ตั้งค่าด้วย setWidth()
  • x - พิกัด x ตั้งค่าด้วย setX()
  • y - พิกัด y ตั้งค่าด้วย setY()

ขั้นตอนสร้าง Rectangle:

  • สร้างอินสแตนซ์คลาส Rectangle
  • ตั้งค่าคุณสมบัติที่ต้องการ ใช้ setter หรือส่งให้คอนสตรัคเตอร์
  • เพิ่มโหนด (shape) ที่สร้างเข้าไปใน Group object

ตัวอย่าง

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.Rectangle;

public class DrawinRectangle extends Application {
    public void start(Stage stage) {
        // วาด Rectangle
        Rectangle shape = new Rectangle();
        shape.setX(150.0f);
        shape.setY(75.0f);
        shape.setWidth(300.0f);
        shape.setHeight(150.0f);
        shape.setFill(Color.DARKCYAN);
        shape.setStrokeWidth(8.0);
        shape.setStroke(Color.DARKSLATEGREY);

        // ตั้งค่า Scene
        Group root = new Group(shape);
        Scene scene = new Scene(root, 595, 300, Color.BEIGE);
        stage.setTitle("Drawing Rectangle");
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String args[]){
        launch(args);
    }
}

ผลลัพธ์

วิธาสร้าง Rectangle ใน JavaFX

Rounded Rectangle

Rectangle class ยังมีคุณสมบัติเพิ่มเติม 2 ตัว:

  • arcWidth - เส้นผ่านศูนย์กลางของโค้งที่มุม 4 มุม ตั้งค่าด้วย setArcWidth()
  • arcHeight - ความสูงของโค้งที่มุม 4 มุม ตั้งค่าด้วย setArcHeight()

การตั้งค่าทั้งคู่จะได้ Rectangle มุมโค้ง:

ตัวอย่าง Rounded Rectangle

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.Rectangle;

public class DrawingRoundedRectangle extends Application {
    public void start(Stage stage) {
        Rectangle shape = new Rectangle();
        shape.setX(150.0f);
        shape.setY(75.0f);
        shape.setWidth(300.0f);
        shape.setHeight(150.0f);
        shape.setArcHeight(30.0);
        shape.setArcWidth(30.0);
        shape.setFill(Color.DARKCYAN);
        shape.setStrokeWidth(8.0);
        shape.setStroke(Color.DARKSLATEGREY);

        Group root = new Group(shape);
        Scene scene = new Scene(root, 595, 300, Color.BEIGE);
        stage.setTitle("Drawing Rectangle");
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String args[]){
        launch(args);
    }
}

ผลลัพธ์

วิธาสร้าง Rectangle ใน JavaFX