如何使用 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