二維形狀(物件)減法運算



此操作將兩個或多個形狀作為輸入。然後,它返回第一個形狀的面積,不包括第二個形狀重疊的面積,如下所示。

Subtraction Operation

您可以使用名為 `subtract()` 的方法對形狀執行減法運算。由於這是一個靜態方法,因此應使用類名(Shape 或其子類)呼叫它,如下所示。

Shape shape = Shape.subtract(circle1, circle2);  

以下是減法運算的示例。在這裡,我們繪製兩個圓圈並對其執行減法運算。

將此程式碼儲存在名為 `SubtractionExample.java` 的檔案中。

示例

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.Circle; 
import javafx.scene.shape.Shape; 
         
public class SubtractionExample extends Application { 
   @Override 
   public void start(Stage stage) {
      //Drawing Circle1 
      Circle circle1 = new Circle();         
      
      //Setting the position of the circle 
      circle1.setCenterX(250.0f); 
      circle1.setCenterY(135.0f); 
      
      //Setting the radius of the circle 
      circle1.setRadius(100.0f); 
      
      //Setting the color of the circle 
      circle1.setFill(Color.DARKSLATEBLUE);     
       
      //Drawing Circle2 
      Circle circle2 = new Circle();         
      
      //Setting the position of the circle 
      circle2.setCenterX(350.0f); 
      circle2.setCenterY(135.0f); 
      
      //Setting the radius of the circle 
      circle2.setRadius(100.0f); 
      
      //Setting the color of the circle 
      circle2.setFill(Color.BLUE);  
       
      //Performing subtraction operation on the circle 
      Shape shape = Shape.subtract(circle1, circle2); 
      
      //Setting the fill color to the result 
      shape.setFill(Color.DARKSLATEBLUE); 
       
      //Creating a Group object  
      Group root = new Group(shape); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Subtraction Example");
      
      //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 SubtractionExample.java 
java SubtractionExample

執行後,上述程式生成一個 JavaFX 視窗,顯示以下輸出:

Subtraction Operation Output
javafx_2d_shapes.htm
廣告
© . All rights reserved.