是画在其他界面不是swing界面上
时间: 2024-10-11 14:10:44 浏览: 17
如果你想在Java的非Swing UI框架(比如JavaFX或AWT/Swing之外的库)上使用鼠标画数字,例如在一个自定义的Canvas或SurfaceView上,你需要稍微调整一下方法。这里以JavaFX为例,因为它的图形API更为现代且功能强大。
1. 首先,导入必要的包:
```java
import javafx.scene.canvas.Canvas;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
```
2. 创建一个Canvas并添加鼠标事件监听器:
```java
public class CustomCanvas extends Canvas {
private Context2D context;
public CustomCanvas(int width, int height) {
setWidth(width);
setHeight(height);
context = getScene().getGraphicsContext2D();
addEventHandler(MouseEvent.MOUSE_CLICKED, this::handleMouseClick);
addEventHandler(MouseEvent.MOUSE_MOVED, this::handleMouseMove);
}
private void handleMouseClick(MouseEvent event) {
draw(event.getX(), event.getY());
}
private void handleMouseMove(MouseEvent event) {
draw(event.getX(), event.getY());
}
private void draw(double x, double y) {
if (context != null) {
context.clearRect(0, 0, getWidth(), getHeight()); // 清除旧的内容
context.setStroke(Color.BLACK);
context.fillText(String.valueOf(Math.abs((int)x - (int)y)), x, y); // 绘制数字
}
}
}
```
3. 在你的主窗口中添加Canvas:
```java
public static void main(String[] args) {
Platform.runLater(() -> {
Stage stage = new Stage();
stage.setScene(new Scene(new CustomCanvas(400, 400)));
stage.setTitle("Custom Canvas");
stage.show();
});
}
```
在这个例子中,每次鼠标点击或移动都会清空Canvas并重新绘制当前的X-Y坐标对应的数字。
阅读全文