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);
}
}
運行這段代碼,將會彈出一個窗口,你可以在窗口內點擊并拖動鼠標左鍵來繪制矩形。