多读书多实践,勤思考善领悟

JavaFX 2D Shapes Rounded Rectangle形状圆角矩形

本文于1668天之前发表,文中内容可能已经过时。

在JavaFX中,您可以绘制具有锐边或带有拱形边的矩形,如下图所示。

带有拱形边缘的那个被称为圆角矩形,它有两个额外的属性,即 -

  • arcHeight - 弧形的垂直直径,位于圆角矩形的角上。
  • arcWidth - 圆角矩形边角处圆弧的水平直径。

默认情况下,除非使用各自的setter方法setArcHeight()setArcWidth()将弧的高度和宽度设置为+ ve值(0 <),否则JavaFX会创建一个具有锐边的矩形。

以下是使用JavaFX生成圆角矩形的程序。将此代码保存在名为RoundedRectangle.java的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import javafx.application.Application; 
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;

public class RoundedRectangle extends Application {
@Override
public void start(Stage stage) {
//Drawing a Rectangle
Rectangle rectangle = new Rectangle();

//Setting the properties of the rectangle
rectangle.setX(150.0f);
rectangle.setY(75.0f);
rectangle.setWidth(300.0f);
rectangle.setHeight(150.0f);

//Setting the height and width of the arc
rectangle.setArcWidth(30.0);
rectangle.setArcHeight(20.0);

//Creating a Group object
Group root = new Group(rectangle);

//Creating a scene object
Scene scene = new Scene(root, 600, 300);

//Setting title to the Stage
stage.setTitle("Drawing a Rectangle");

//Adding scene to the stage
stage.setScene(scene);

//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

使用以下命令从命令提示符编译并执行保存的java文件。

1
2
javac RoundedRectangle.java 
java RoundedRectangle

在执行时,上述程序生成一个显示圆角矩形的JavaFX窗口,如下所示。