是否可以在 JavaFX 中将 ImageView 放在 Canvas 上?

2022-01-20 00:00:00 canvas popup java javafx imageview

我是 javafx 的新手.我正在开发一个应用程序,其中有一个画布,并在其中绘制了几张图像.我想在我的画布上添加一个 ImageView 并在单击 ImageView 时实现一个弹出窗口?

I am a newbie to javafx. I am developing an application in which I have a canvas and I have drawn several images in it. I want to add an ImageView on my canvas and implement a popup while clicking on the ImageView?

是否有可能使用或不使用 ImageView(按钮或任何控件?)或者是否仅限于在画布上使用控件?

Is there any possibilities with or without ImageView (buttons or any controls?) or is it restricted to use controls over canvas?

我需要一些建议.

推荐答案

您可以将 ImageView 堆叠在 Canvas 之上.使用 StackPane.您可以稍后将鼠标侦听器添加到 ImageView.

You can stack an ImageView on top of a Canvas. Use a StackPane. You can later add mouse listeners to the ImageView.

是否有可能使用或不使用 ImageView(按钮或任何控件?)或者是否仅限于在画布上使用控件?

Is there any possibilities with or without ImageView (buttons or any controls?) or is it restricted to use controls over canvas?

所有控件,包括 ButtonImageViewCanvas 本身都从 Node 可用于在StackPane.

All controls including Button, ImageView and Canvas itself extend from Node and can be used to add in the StackPane.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

    int count = 1;

    @Override
    public void start(Stage stage) {

        StackPane root = new StackPane();
        Scene s = new Scene(root, 400, 400, Color.BLACK);

        final Canvas canvas = new Canvas(300, 300);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        gc.setFill(Color.BLUE);
        gc.fillRect(10, 10, 300, 300);

        ImageView image = new ImageView("https://cdn0.iconfinder.com/data/icons/toys/256/teddy_bear_toy_6.png");

        // Listener for MouseClick
        image.setOnMouseClicked(e -> {
            Stage popup = new Stage();
            popup.initOwner(stage);
            popup.show();
        });

        root.getChildren().addAll(canvas, image);

        stage.setScene(s);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

输出:

  • 场景有黑色背景
  • 画布有蓝色背景
  • ImageView 是熊.

相关文章