好的,以下是一份使用JavaFX和GUI知识重写的代码示例,它可以创建一个窗口,在窗口中显示一个按钮和一个画布,在画布上使用鼠标绘制图形。写以上代码
时间: 2024-02-27 20:53:43 浏览: 67
好的,以下是一份使用JavaFX和GUI知识重写的代码示例,它可以创建一个窗口,在窗口中显示一个按钮和一个画布,在画布上使用鼠标绘制图形。
```
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DrawingApp extends Application {
private GraphicsContext graphicsContext;
private double lastX, lastY;
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
// 创建一个画布
Canvas canvas = new Canvas(400, 400);
graphicsContext = canvas.getGraphicsContext2D();
graphicsContext.setStroke(Color.BLACK);
graphicsContext.setLineWidth(2);
// 添加画布到布局
root.setCenter(canvas);
// 创建一个按钮
Button clearButton = new Button("Clear");
// 添加按钮到布局
HBox toolbar = new HBox();
toolbar.getChildren().add(clearButton);
root.setBottom(toolbar);
// 添加鼠标事件
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
lastX = event.getX();
lastY = event.getY();
}
});
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
double x = event.getX();
double y = event.getY();
graphicsContext.strokeLine(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
});
// 添加清除按钮事件
clearButton.setOnAction(event -> {
graphicsContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
});
primaryStage.setTitle("Drawing App");
primaryStage.setScene(new Scene(root, 400, 450));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这段代码中,我们使用了JavaFX的布局和控件来创建窗口和按钮,使用Canvas来创建画布。我们也添加了鼠标事件来响应用户的绘制操作。
阅读全文
相关推荐














