首页 > 解决方案 > 如何访问动作事件处理程序(javafx 按钮)中的外部变量?

问题描述

我有点 javafx 菜鸟。我想让这个按钮更新名为“viewGraph”的“GraphView”对象,但我不知道如何正确执行此操作,因为我无法访问 setOnAction 事件中的外部变量。我也想在事件类之外创建 startVertice 和 endVertice,但我不知道该怎么做。

我认为答案是以某种方式在使用参数中传递变量,但我不知道该怎么做。

我尝试查找内容并尝试随机语法内容,但我仍然不知道该怎么做。不过看起来很简单。

WeightedGraph<Campus> graph = new WeightedGraph<>(vertices, edges);

        Label startCampus = new Label("Starting Campus: ");
        Label endCampus = new Label("    Ending Campus: ");
        TextField startText = new TextField();
        TextField endText = new TextField();
        Button displayShortestPathBtn = new Button("Display Shortest Path");

        HBox input = new HBox();
        input.getChildren().addAll(startCampus, startText, endCampus, endText, displayShortestPathBtn);
        input.setPadding(new Insets(25, 0, 0, 0));

        VBox vbox = new VBox();
        GraphView viewGraph = new GraphView(graph);
        vbox.getChildren().addAll(viewGraph, input);
        vbox.setPadding(new Insets(50, 50, 25, 50));


        displayShortestPathBtn.setOnAction((event) -> {
            int startVertice = Integer.parseInt(startText.getText());
            int endVertice = Integer.parseInt(endText.getText());

            WeightedGraph<Campus>.ShortestPathTree shortestPathGraph = graph.getShortestPath(startVertice);
            ArrayList<Integer> path = (ArrayList)shortestPathGraph.getPath(endVertice);

            /*
            What I want to do:

            viewGraph = new GraphView(graph, path);
            */
        });

        primaryStage.setTitle("Final Exam");
        primaryStage.setScene(new Scene(vbox));
        primaryStage.show();

我只想能够访问外部变量,但如果可能的话,或者如果我首先正确地解决了问题,我想知道。

标签: javajavafx

解决方案


推荐阅读