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

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

问题描述:

我是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?

所有控件包括 Button ImageView Canvas 本身从 节点 并可用于添加 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是熊。