JavaFX8空指针从控制器加载FXML文件时出现异常

时间:2017-08-28 18:07:57

标签: javafx-8

我有一个StackPane作为我的根,并在Main Application Start()方法中加载了BorderPane布局。 在BorderPane布局中,我有2个按钮:一个用于添加fxml文件(Menu.fxml),另一个用于删除此文件。 一旦加载了Menu.fxml,我在Menu.fxml中有一个按钮,当点击它时,应该在先前加载的BorderPane布局的中心加载一个fxml文件(One.fxml)。 但是,在这个阶段我得到一个空指针异常。你能指出我哪里出错了。 谢谢。

以下是我的代码:

public class Main extends Application {

    private static StackPane rootStack;
    private static BorderPane rootBorder;

    @Override
    public void start(Stage stage) throws Exception {
        rootStack = FXMLLoader.load(getClass().getResource("Base.fxml"));
        rootBorder = FXMLLoader.load(getClass().getResource("Border.fxml"));
        rootStack.getChildren().addAll(rootBorder);

        Scene scene = new Scene(rootStack);
        stage.setScene(scene);
        stage.show();
    } // start

    public static StackPane getRootStack() {
        return rootStack;
    } // end of method getRootStack

    public static BorderPane getRootBorder() {
        return rootBorder;
    } // end of method getRootBorder

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

} // Main
public class BorderController {

    private StackPane rootStack = Main.getRootStack();
    VBox menu;

    public void initialize() throws IOException {
        menu = FXMLLoader.load(getClass().getResource("Menu.fxml"));
    } // initialize    

    @FXML
    private void addMenuPane(ActionEvent event) throws IOException {
        rootStack.getChildren().add(menu);
    } // addMenuPane

    @FXML
    private void removeNode(ActionEvent event) {
        rootStack.getChildren().remove(menu);
    } // removeNode

} // BorderController
public class MenuController {

    private BorderPane rootBorder = Main.getRootBorder();

    @FXML
    private JFXButton oneButton;

    public void initialize() {
        oneButton.addEventHandler(MouseEvent.MOUSE_CLICKED, (event) -> {
            try {
                rootBorder.setCenter(FXMLLoader.load(getClass().getResource("One.fxml")));
            } catch (IOException ex) {
                Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex);
            }
        });

    } // initialize    

} // MenuController

堆栈追踪:

Executing C:\Users\User\Documents\NetBeansProjects\Stack\dist\run2093523570\Stack.jar using platform C:\Program Files\Java\jdk1.8.0_121\jre/bin/java
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at stack.MenuController.lambda$initialize$0(MenuController.java:22)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Deleting directory C:\Users\User\Documents\NetBeansProjects\Stack\dist\run2093523570

1 个答案:

答案 0 :(得分:3)

当您加载FXML文件时,如果FXML文件的根元素具有fx:controller属性,则实例化该属性指定的类,注入任何@FXML - 注释字段,并且在控制器类实例(如果有)上调用initialize()方法。所有这些都是load()的{​​{1}}方法的一部分。

如果您考虑FXMLLoader方法中的代码行:

Application.start()

这将加载rootBorder = FXMLLoader.load(getClass().getResource("Border.fxml")); ,创建控制器,调用其Border.fxml方法等,并且只有完成所有操作后才会将结果分配给initialize()。调用的rootBorder中的initialize()方法会加载BorderController;反过来,实例化Menu.fxml中的控制器(我假设)是Menu.fxmlMenuController的初始化代码包括

MenuController

请注意,此时,加载private BorderPane rootBorder = Main.getRootBorder(); 的{​​{1}}方法仍未完成,因此load()中的静态Border.fxml字段尚未完成已分配,因此rootBorder会返回Main

因此,稍后当你尝试

Main.getRootBorder()

由于为null分配了值rootBorder.setCenter(...); ,因此会出现空指针异常。

快速而肮脏的修复只是在您需要时检索边框窗格:

rootBorder

然而,这种在null子类中使用静态字段的方法是一个非常糟糕的设计。你介绍了各种不必要的耦合(你的public class MenuController { @FXML private JFXButton oneButton; public void initialize() { oneButton.addEventHandler(MouseEvent.MOUSE_CLICKED, (event) -> { try { Main.getRootBorder().setCenter(FXMLLoader.load(getClass().getResource("One.fxml"))); } catch (IOException ex) { Logger.getLogger(MenuController.class.getName()).log(Level.SEVERE, null, ex); } }); } // initialize } // MenuController 真的应该依赖于特定的Application类的存在吗?)并暴露不应该暴露的各种UI元素(假设您想在某个时候更改整体布局;您基本上需要更改整个UI代码库)。您可能应该对此进行重组以避免需要以这种方式执行操作。