HOWTO · Java
JavaFX에서 캔버스 지우기
이 튜토리얼에서는 JavaFX에서 캔버스를 지우는 방법을 살펴봅니다.
이 페이지의 내용
JavaFX에서 캔버스는 일련의 그래픽 명령을 사용하여 다양한 모양과 구성 요소를 그리는 이미지와 같습니다. 이 노드는 필요한 높이와 무게로 구성됩니다.
JavaFX 캔버스를 사용하여 사각형, 타원, 원 등 다양한 도형을 화면에 그릴 수 있는 UI 컴포넌트를 생성할 수 있습니다. 그 특별한 UI 구성 요소를 캔버스라고 합니다.
그러나 때로는 캔버스에서 그림을 제거하거나 수정해야 합니다.
이 기사에서는 캔버스를 제거하거나 지우는 방법을 살펴보겠습니다. 또한 이해하기 쉽도록 필요한 코드 및 설명과 함께 이 주제에 대해 논의합니다.
JavaFX에서 캔버스 지우기
clearRect()라는 메서드를 사용하면 특정 구성 요소를 제거하거나 캔버스를 지울 수 있습니다. 자세히 논의합시다.
캔버스에 타원을 만들려면 아래 코드를 사용할 수 있습니다.
Diameter = Math.max(Width,
Height); // Create a mathematical calculation for the ovel with necessary height an weight
if (filledColor == null)
g.drawOval(x, y, Width, Height); // Draw the oval without fill it with color
else
g.fillOval(x, y, Width, Height); // Draw the oval and fill it with color
break;
프로그램에 이 코드를 포함하면 캔버스에 타원이 그려지는 것을 볼 수 있습니다. 캔버스에서 타원을 제거하거나 캔버스를 지우려면 아래 코드를 사용할 수 있습니다.
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
위에서 공유한 코드는 그림을 제거하고 화면을 지웁니다.
이 방법의 일반적인 형식은 다음과 같습니다.
clearRect( X_Position, Y_Position, Canvas_Height, Canvas_Width )
캔버스를 지우는 데만 사용할 버튼의 작업으로 이것을 포함할 수 있습니다.
아래는 이 방법을 사용하는 간단한 캔버스의 예입니다.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class FxCanvas extends Application {
public static void main(String[] args) {
Application.launch(args); // Launch the application
}
@Override
public void start(Stage PrimaryStage) {
Canvas canvas = new Canvas(500, 200); // Create the Canvas
GraphicsContext g = canvas.getGraphicsContext2D(); // Create a 2D graphics context on the canvas
g.setLineWidth(3.0); // Set line width
g.setFill(Color.RED); // Set fill color
g.fillRoundRect(50, 50, 300, 100, 10, 10); // Draw a rounded Rectangle on the canvas
g.clearRect(80, 80, 140, 50); // Clear the rectangular area from the canvas
Pane pn = new Pane(); // Create a Pane
// Provide necessary styles
pn.setStyle(
"-fx-padding: 10; -fx-border-style: solid inside; -fx-border-width: 2; -fx-border-insets: 5; -fx-border-radius: 5; -fx-border-color: blue;");
pn.getChildren().add(canvas); // Add the canvas to the Pane
Scene scene = new Scene(pn); // Create a Scene
PrimaryStage.setScene(scene); // Add the Scene to the Stage
PrimaryStage.setTitle("Clearing Canvas area"); // Set the title of the application
PrimaryStage.show(); // Display the Stage
}
}
위의 예제 코드를 컴파일하고 환경에서 실행하면 아래 출력이 표시됩니다.
출력:
IDE가 라이브러리 및 패키지의 자동 포함을 지원하지 않는 경우 기억하십시오. 그런 다음 이러한 필수 라이브러리 및 패키지를 수동으로 컴파일하기 전에 포함해야 할 수 있습니다.