如何使用 JavaFX 建立矩形?
矩形是一個封閉的多邊形,具有四個邊,任意兩邊之間的角為直角,並且相對邊是共線的。它由其高度和寬度定義,分別為垂直和水平邊的長度。
在 JavaFX 中,矩形由 **javafx.scene.shape.Rectangle** 類表示。此類包含四個屬性,它們是 -
**height** - 此屬性表示圓心橫座標,您可以使用 **setHeight()** 方法為此屬性設定值。
**width** - 此屬性表示圓心縱座標,您可以使用 **setWidth()** 方法為此屬性設定值。
**x** - 圓的半徑(以畫素為單位),您可以使用 **setRadius()** 方法為此屬性設定值。
**y** - 圓的半徑(以畫素為單位),您可以使用 **setRadius()** 方法為此屬性設定值。
要建立矩形,您需要 -
例項化 Rectangle 類。
使用 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.Rectangle;
public class DrawinRectangle extends Application {
public void start(Stage stage) {
//Drawing a Rectangle
Rectangle shape = new Rectangle();
//Setting the properties of the rectangle
shape.setX(150.0f);
shape.setY(75.0f);
shape.setWidth(300.0f);
shape.setHeight(150.0f);
//Setting other properties
shape.setFill(Color.DARKCYAN);
shape.setStrokeWidth(8.0);
shape.setStroke(Color.DARKSLATEGREY);
//Setting the 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 類還提供了另外兩個屬性,即 -
**arcWidth** - 此屬性表示 4 個角處的圓弧直徑。您可以使用 **setArcWidth()** 方法設定其值。
**arcHeight** - 此屬性表示 4 個角處的圓弧高度。您可以使用 **setArcHeight()** 方法設定其值。
透過為這些屬性設定值,您可以繪製一個具有圓角/圓弧邊的矩形 -
示例
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) {
//Drawing a Rectangle
Rectangle shape = new Rectangle();
//Setting the properties of the 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);
//Setting other properties
shape.setFill(Color.DARKCYAN);
shape.setStrokeWidth(8.0);
shape.setStroke(Color.DARKSLATEGREY);
//Setting the 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);
}
}輸出

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP