NullPointerException 尽管 fx:id 和 fx:controller 是正确的

我正在为我的 lan 应用程序创建包含日志的表。当我尝试运行此应用程序时,它会抛出 NullPointerException,但 fx:id 和 fx:controller 是正确的。我正在使用 JavaFX 12。


我尝试使用 Intellij 重构 fx:id 和 fx:controller,Intellij 也在 logPane.fxml 和 LogPaneController.class 中正确地更改了它,但它仍然无法正常工作。如果我注释掉异常所在的行,则所有应用程序都可以正常工作。我用谷歌搜索短语“FXML 组件返回 NUllPointerException”,但结果始终是“您的 fx:id 或 fx:controller 名称在控制器中不相同”。


日志面板.fxml


<?xml version="1.0" encoding="UTF-8"?>


<?import javafx.scene.control.*?>

<?import javafx.scene.layout.*?>

<AnchorPane HBox.hgrow="ALWAYS" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1"

            fx:controller="com.lanssmaker.controller.LogPaneController">

    <children>

        <TableView fx:id="logTable" prefHeight="574.0" prefWidth="382.0" AnchorPane.bottomAnchor="0.0"

                   AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">

            <columns>

                <TableColumn maxWidth="140.0" minWidth="70" prefWidth="70.0" text="Time"/>

                <TableColumn text="Content"/>

                <TableColumn maxWidth="140.0" minWidth="70" prefWidth="70.0" text="Category"/>

            </columns>

            <columnResizePolicy>

                <TableView fx:constant="CONSTRAINED_RESIZE_POLICY"/>

            </columnResizePolicy>

        </TableView>

    </children>

</AnchorPane>

LogPaneController.class


public class LogPaneController {


    @FXML

    private TableView<Log> logTable; //it's null


    public TableView<Log> getLogTableView() {

        return logTable;

    }



    public void initialize() {

        //example ussage calling NullPointerException

        logTable.isHover();

    }

}


慕工程0101907
浏览 170回答 2
2回答

子衿沉夜

仔细查看堆栈跟踪:...Caused by: javafx.fxml.LoadException:&nbsp;/D:/Programming/Java/javastart/ssmaker/target/classes/fxml/buttonsPane.fxml/D:/Programming/Java/javastart/ssmaker/target/classes/fxml/mainPane.fxml:17...Caused by: java.lang.NullPointerException&nbsp; &nbsp; at ssmaker/com.lanssmaker.controller.LogPaneController.initialize(LogPaneController.java:25)这意味着当您加载buttonsPane.fxml时发生异常FXMLLoader<fx:include source="buttonsPane.fxml"/>元素。此外,它告诉我您不仅使用LogPaneControllerfor logPane.fxml,还使用 for buttonsPane.fxml。每次加载 fxml 时都会创建单独的控制器实例;使用<fx:include>结果FXMLLoader会创建一个单独的实例来加载包含的 fxml。logTable仅为其中之一注入该字段;对于其他控制器实例,它仍然存在null。buttonsPane.fxml(这甚至忽略了加载发生在加载之前的事实logPane.fxml,所以即使在加载buttonsPane.fxml完成时使用了相同的控制器实例,也TableView没有基于创建logPane.fxml。)buttonsPane.fxml为和使用单独的控制器类logPane.fxml。您不会通过简单地使用相同的控制器类来让两个 fxml“进行通信”。我会建议一个替代方案,但你在那里做的事情没有任何意义(除非你试图挑起 NPE):isHover简单地重新调整属性的值hover,该属性始终false用于尚未属于 a 的节点Scene。

30秒到达战场

你有私有 logTable 的 getter 类,所以你可以获得一个值,但我没有看到值初始化或 setter 类(它将初始化值)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java