当前位置: 首页 > 知识库问答 >
问题:

JavaFX FileChooser在调用时引发NullPointerException

公冶子安
2023-03-14

当我调用EmailSenderController上的addHtml()方法将html文件文本添加到html编辑器时,会引发错误。

类似的线程,但例外是我没有像他那样初始化@fxml inject控件:JavaFX FileChooser抛出错误(可能很容易修复,但仍然混乱)

主类

package emailsender;

import configuration.ProjectConfiguration;
import emailsender.controllers.EmailSenderController;
import emailsender.services.FileReaderService;
import emailsender.services.ViewLoaderService;
import java.io.IOException;
import javafx.application.Application;
import javafx.stage.Stage;

/**
 *
 * @author DJava
 */
public class EmailSender extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException, Exception 
    {

        //Main configuration
        ProjectConfiguration configuration = new 
        ProjectConfiguration();
        configuration.setStage(primaryStage);
        configuration.setViewsPath("emailsender/views/");

        //Services
        ViewLoaderService viewloaderService = new 
        ViewLoaderService(configuration);
        FileReaderService fileReaderService = new 
        FileReaderService(configuration);

        //Controllers
        EmailSenderController sender = new 
        EmailSenderController(viewloaderService, fileReaderService);
        sender.start(configuration.getStage());
        }

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

    }
    package emailsender.services;

import configuration.ProjectConfiguration;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;

/**
 *
 * @DJava
 */
public class ViewLoaderService {

    ProjectConfiguration configuration;

    public ViewLoaderService(ProjectConfiguration configuration) {

        this.configuration = configuration;
    }

    public Scene loadViewOnScene(String view) throws IOException {

        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource(this.configuration.getViewsPath() + view + ".fxml"));
        return new Scene(root);
    }

}
package emailsender.controllers;

import emailsender.services.FileReaderService;
import javafx.application.Application;
import javafx.stage.Stage;
import emailsender.services.ViewLoaderService;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

/**
 *
 * @author DJava
 */
public class EmailSenderController extends Application {

    private ViewLoaderService viewLoaderService;
    private FileReaderService fileReaderService;
    private WebEngine webEngine;

    //Header
    //EmaiLSender menu
    @FXML
    public MenuItem newListMenuItem;
    @FXML
    public MenuItem preferencesMenuItem;
    @FXML
    public MenuItem closeMenuItem;

    //Help menu
    @FXML
    public MenuItem aboutMenuItem;

    //Email tab
    @FXML
    public TextField subjectTextField;
    @FXML
    public ComboBox destinationListComboBox;
    @FXML
    public Button addHtmlButton;
    @FXML
    public HTMLEditor messageEditor;
    @FXML
    public ProgressIndicator sendTaskProgressIndicator;

    //Preview tab
    @FXML
    public WebView previewWebView;

    //Footer
    @FXML
    public Button sendButton;

    public EmailSenderController() {
    }

    public EmailSenderController(ViewLoaderService viewLoaderService, 
    FileReaderService fileReaderService) {

        this.viewLoaderService = viewLoaderService;
        this.fileReaderService = fileReaderService;
    }

    @FXML
    public void addHtml() {

    this.messageEditor.setHtmlText
    (this.fileReaderService.getFileText()); // Here is the problem ..........
    }

    @FXML
    public void previewEmail() {

        this.webEngine = this.previewWebView.getEngine();
        this.webEngine.loadContent(this.messageEditor.getHtmlText());
    }

    @FXML
    public void sendEmail() {

        this.sendTaskProgressIndicator.setProgress(0.3D);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        primaryStage.setTitle("EmailSender");
        primaryStage.setScene(viewLoaderService.loadViewOnScene("EmailSender"));
        primaryStage.setResizable(false);
        primaryStage.show();
    }

}
package emailsender.services;

import configuration.ProjectConfiguration;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javafx.stage.FileChooser;

/**
 *
 * @author DJava
 */
public class FileReaderService {

    private final ProjectConfiguration configuration;
    private final FileChooser fileChooser;

    public FileReaderService(ProjectConfiguration configuration) {

        this.configuration = configuration;
        this.fileChooser = new FileChooser();
    }

    public String getFileText() {

        String text = "";

        try {

            BufferedReader reader = new BufferedReader(new FileReader(this.fileChooser.showOpenDialog(this.configuration.getStage())));
            String line;
            while ((line = reader.readLine()) != null) {

                text += line + "\n";
            }

        } catch (IOException event) {
            event.printStackTrace();
        }
        System.out.println(text);
        return text;
    }

}
    Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    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.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:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    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.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$MouseHandler.process(Scene.java:3757)
    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:394)
    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$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 49 more
Caused by: java.lang.NullPointerException
    at emailsender.controllers.EmailSenderController.addHtml(EmailSenderController.java:77)
    ... 59 more

共有1个答案

翟迪
2023-03-14

问题是执行addhtml方法的控制器与最初创建的控制器不同。加载电子邮件发送器时,FXMLLoader使用空构造函数创建新控制器。因此,设置属性的构造函数不会被调用,最终会得到null属性。

要获得正确的控制器,请使用加载器的getController方法,并使用适当的set方法设置属性:

FXMLLoader loader = new FXMLLoader("fxml file") ;
loader.load();
EmailSenderController controller = (EmailSenderController)  loader .getController() ;
controller.setFileReadService(frs) ; // frs created elsewhere

另外,您的类架构有点奇怪。您应该只有一个application类。控制器永远不应该是应用程序类。它的工作是控制一个视图,而不是运行整个窗口。建议您更改配置以加载视图和控制器,如上所示。控制器属性必须在加载视图后立即设置。

 类似资料:
  • 我已经创建了3个片段,在一个ViewPager中。我试图仅当特定片段对用户可见时才从服务器获取数据。为此,我在setUserVisibleHint()中调用了web服务方法。但是当我在该方法内部使用getActivity()时,我会得到NullPointerException。我如何确保我只加载一次数据并且当它对用户可见时?代码如下: 我已经验证了在setUserVisibleHint()之后调用

  • 我目前正在尝试用JDA编写一个非常基本的Discord bot,在试图将代码整齐地分为一个Main类、、和类时,我遇到了一个问题。 如果接收到事件,主类将添加EventListener来调用MessageHandler,然后如果在命令之前看到bot前缀,则分支到CommandHandler。 问题是,当它试图用调用CommandHandler时,会抛出一个NullPointerException。

  • 我有几个Drools项目,希望能够动态加载规则的变化。在我尝试将KieScanner添加到它们之前,这些项目都工作得很好。我遵循了以下说明:http://docs.jboss.org/drools/release/6.0.1.final/drools-docs/html/droolsreleasenoteschapter.html#d0e515 我使用drools 6.1.0。final和Wild

  • 问题内容: 假设我希望能够在程序中任何地方每次引发异常时都能够记录到文件。我不想修改任何现有代码。 当然,可以将其概括为每次引发异常时都可以插入钩子。 以下代码是否被认为可以安全地执行此操作? 问题答案: 如果要记录 未捕获的 异常,只需使用sys.excepthook即可。 我不确定是否会记录 所有 引发的异常的价值,因为很多库会在内部为可能不关心的事情引发/捕获异常。

  • 我有以下错误 ValidationException:HV000041:调用TraversableResolver.IsReachable()引发异常。在org.hibernate.validator.internal.engine.validatorimpl.isreachable(validatorimpl.java:1405)上 org.hibernate.validator.interna