Java: Thao tác Subtraction
Giải phóng thời gian, khai phóng năng lực
Thao tác Subtraction lấy hai hoặc nhiều hình dạng làm đầu vào. Sau đó, nó trả về diện tích của hình đầu tiên trừ diện tích bị hình thứ hai chồng lên như hình bên dưới.
Bạn có thể thực hiện Phép toán trừ trên các hình dạng bằng phương thức có tên là subtract(). Vì đây là một phương thức tĩnh, bạn nên gọi nó bằng tên lớp (Hình dạng hoặc các lớp con của nó) như hình dưới đây.
Shape shape = Shape.subtract(circle1, circle2);
Sau đây là một ví dụ về phép toán trừ. Ở đây, chúng tôi đang vẽ hai hình tròn và thực hiện một phép tính trừ trên chúng.
Lưu mã này trong một tệp có tên SubtractionExample.java .
Thí dụ
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); } }
Biên dịch và thực thi tệp java đã lưu từ dấu nhắc lệnh bằng các lệnh sau.
javac SubtractionExample.java java SubtractionExample
Khi thực thi, chương trình trên tạo một cửa sổ JavaFX hiển thị kết quả sau:
Giải phóng thời gian, khai phóng năng lực