Java

Java如何实现画图板功能

小亿
114
2023-08-18 17:37:35
栏目: 编程语言

Java可以使用JavaFX或Swing来实现画图板功能。下面是一个简单的示例代码,演示如何使用JavaFX实现一个简单的画图板:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DrawingBoard extends Application {
private double startX, startY, endX, endY;
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(800, 600);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setStroke(Color.BLACK);
gc.setLineWidth(1.0);
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton() == MouseButton.PRIMARY) {
startX = event.getX();
startY = event.getY();
}
});
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, event -> {
if (event.getButton() == MouseButton.PRIMARY) {
endX = event.getX();
endY = event.getY();
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
gc.strokeRect(startX, startY, endX - startX, endY - startY);
}
});
VBox root = new VBox(canvas);
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("Drawing Board");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

运行这段代码,将会弹出一个窗口,你可以在窗口内点击并拖动鼠标左键来绘制矩形。

0
看了该问题的人还看了