在 JavaFX 的选项卡中实现绘图区域

Implementing drawing areas in tabs in JavaFX

我想在 JavaFX 的选项卡中添加一个绘图区。我是该领域的新手,并尝试向我创建的每个选项卡添加 Canvas。但是,这似乎不起作用。包含相关代码。

@FXML
void fileNewTabHandler(ActionEvent event) {
    ++indexTab;
    Tab tab = new Tab("Untitled " + indexTab);
    Canvas canvas = new Canvas(500, 285);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.setFill(Color.BLUE);
    gc.fillRect(250, 856, 50, 60);
    tab.setContent(canvas);
    tabPane.getTabs().add(tab);
}

这里定义了 tabPane 和 indexTab,只要我不使用 canvas 就可以工作。我哪里错了。我应该使用不同的方法来实现我想要的吗?

快速示例

这并没有真正的技巧,您只需将 canvas 设置为选项卡的内容即可。

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.Random;

public class TabbedCanvas extends Application {

    private int tabId = 0;
    private double W = 200, H = 150;

    private Random random = new Random(42);

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        Button newTabButton = new Button("New Tab");
        newTabButton.setOnAction(
                event -> addTab(tabPane)
        );
        newTabButton.fire();

        ToolBar toolBar = new ToolBar(newTabButton);
        toolBar.setMinHeight(ToolBar.USE_PREF_SIZE);

        VBox layout = new VBox(toolBar, tabPane);
        VBox.setVgrow(tabPane, Priority.ALWAYS);
        stage.setScene(new Scene(layout));
        stage.show();
    }

    private void addTab(TabPane tabPane) {
        Tab tab = new Tab("Tab: " + tabId++);
        tab.setContent(createTabContent());
        tabPane.getTabs().add(tab);
        tabPane.getSelectionModel().select(tab);
    }

    private Node createTabContent() {
        Canvas canvas = new Canvas(W, H);

        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(randomColor());
        gc.fillRect(0, 0, W, H);

        return canvas;
    }

    private Color randomColor() {
        return Color.rgb(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256)
        );
    }

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