JavaFX - 二維圖形 圓角矩形



在 JavaFX 中,您可以繪製一個具有銳利邊緣或拱形邊緣的矩形,如下面的圖所示。

Rounded Rectangle

具有拱形邊緣的矩形稱為圓角矩形,它有兩個附加屬性,即:

  • arcHeight - 圓角矩形角部的弧線的垂直直徑。

  • arcWidth - 圓角矩形角部的弧線的水平直徑。

Arc Width Height

預設情況下,JavaFX 建立一個具有銳利邊緣的矩形,除非您使用其各自的 setter 方法 setArcHeight()setArcWidth() 將弧線的高度和寬度設定為正值 (0<)。

示例

下面是一個使用 JavaFX 生成圓角矩形的程式。將此程式碼儲存在名為 RoundedRectangle.java 的檔案中。

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 檔案。

javac RoundedRectangle.java 
java RoundedRectangle

執行上述程式後,會生成一個 JavaFX 視窗,顯示如下所示的圓角矩形。

Drawing Rounded Rectangle
javafx_2d_shapes.htm
廣告
© . All rights reserved.