JavaFX: Exception in thread “JavaFX Application Thread” java.lang.RuntimeException: java.lang.reflect.InvocationTargetException Ask Question

huangapple go评论182阅读模式
英文:

JavaFX: Exception in thread “JavaFX Application Thread” java.lang.RuntimeException: java.lang.reflect.InvocationTargetException Ask Question

问题

我正在尝试创建一个简单的程序,以便在两个字段中接收用户输入,然后将其保存为字符串并写入文件。

我遇到了一个我不认识的错误,而且无论我怎么找问题,都找不到。希望有人能够解释一下。

我的Controller.java文件:

package sample;

import java.io.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

public class Controller {

    @FXML
    private TextField InputEmail;

    @FXML
    private TextField InputName;

    // 输出写入的字符串
    public String Output;

    public void handleButtonAction(ActionEvent event) {
        Output = "Student Name: " + InputName.getText() + "|| Student Email: " + InputEmail.getText() + "\n";
    }

    public void Add(ActionEvent event) {
        try {
            FileWriter fw = new FileWriter("D:/Assignment3&4_Output.txt");
            fw.write(Output);
            System.out.println("File updated");
        } catch (IOException e) {
            System.out.println("File could not be found. Please check the file path.");
        }
    }
}

我的sample.fxml文件:

<!-- 略 -->

我的Main.java文件:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;

public class Main extends Application {

    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

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

当我尝试使用 "Add" 按钮并写入表单时,会抛出以下错误:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    ...
Caused by: java.lang.reflect.InvocationTargetException
    ...
Caused by: java.lang.NullPointerException
    ...

如果有人能提供帮助,我将非常感激,因为我是新手。

英文:

Im trying to create a simple program to take user input in 2 fields, then save it as a string and write it to a file.

Im getting an error that I dont recognize and cant find the problem anywhere, hopefully someone can explain it to me.

My Controller.Java

        import java.io.*;
        import javafx.event.ActionEvent;
        import javafx.fxml.FXML;
        import javafx.scene.control.Button;
        import javafx.scene.control.TextField;


public class Controller {


    @FXML
    private TextField InputEmail;

    @FXML
    private TextField InputName;

    //Output writer String
    public String Output;


    public void handleButtonAction(ActionEvent event) {
        Output = &quot;Student Name: &quot; + InputName.getText() + &quot;|| Student Email: &quot; + InputEmail.getText() + &quot;\n&quot;;
    }

    public void Add(ActionEvent event) {
        try {
            FileWriter fw = new FileWriter(&quot;D:/Assignment3&amp;4_Output.txt&quot;);
            fw.write(Output);
            System.out.println(&quot;File updated&quot;);
        } catch (IOException e) {
            System.out.println(&quot;File could not be found. Please check the file path.&quot;);


        }
    }
}

My sample.fxml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;?import java.lang.*?&gt;
&lt;?import javafx.scene.control.*?&gt;
&lt;?import javafx.scene.layout.*?&gt;
&lt;?import javafx.scene.text.*?&gt;

&lt;GridPane alignment=&quot;center&quot; hgap=&quot;10&quot; vgap=&quot;10&quot; xmlns=&quot;http://javafx.com/javafx/8&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;sample.Controller&quot;&gt;
   &lt;children&gt;
      &lt;SplitPane dividerPositions=&quot;0.25252525252525254, 0.5252525252525253&quot; orientation=&quot;VERTICAL&quot; prefHeight=&quot;200.0&quot; prefWidth=&quot;160.0&quot;&gt;
        &lt;items&gt;
          &lt;AnchorPane minHeight=&quot;0.0&quot; minWidth=&quot;0.0&quot; prefHeight=&quot;100.0&quot; prefWidth=&quot;160.0&quot;&gt;
               &lt;children&gt;
                  &lt;Label layoutX=&quot;12.0&quot; layoutY=&quot;12.0&quot; text=&quot;Create Student&quot; textFill=&quot;#32d9ff&quot;&gt;
                     &lt;font&gt;
                        &lt;Font name=&quot;Arial&quot; size=&quot;20.0&quot; /&gt;
                     &lt;/font&gt;
                  &lt;/Label&gt;
               &lt;/children&gt;
            &lt;/AnchorPane&gt;
          &lt;AnchorPane minHeight=&quot;0.0&quot; minWidth=&quot;0.0&quot; prefHeight=&quot;100.0&quot; prefWidth=&quot;160.0&quot;&gt;
               &lt;children&gt;
                  &lt;TextField id=&quot;InputName&quot; fx:id=&quot;InputName&quot; layoutX=&quot;5.0&quot; layoutY=&quot;13.0&quot; onInputMethodTextChanged=&quot;#handleButtonAction&quot; promptText=&quot;Student Firstname&quot; /&gt;
               &lt;/children&gt;
            &lt;/AnchorPane&gt;
            &lt;AnchorPane layoutX=&quot;10.0&quot; layoutY=&quot;10.0&quot; minHeight=&quot;0.0&quot; minWidth=&quot;0.0&quot; prefHeight=&quot;68.0&quot; prefWidth=&quot;158.0&quot;&gt;
               &lt;children&gt;
                  &lt;TextField id=&quot;InputEmail&quot; fx:id=&quot;InputEmail&quot; layoutX=&quot;5.0&quot; layoutY=&quot;14.0&quot; onAction=&quot;#handleButtonAction&quot; promptText=&quot;Student Email&quot; /&gt;
                  &lt;Button id = &quot;button&quot; fx:id=&quot;button&quot; layoutX=&quot;60.0&quot; layoutY=&quot;46.0&quot; mnemonicParsing=&quot;false&quot; text=&quot;Add&quot; onAction=&quot;#Add&quot; /&gt;
               &lt;/children&gt;
            &lt;/AnchorPane&gt;
        &lt;/items&gt;
      &lt;/SplitPane&gt;
   &lt;/children&gt;
   &lt;columnConstraints&gt;
      &lt;ColumnConstraints /&gt;
   &lt;/columnConstraints&gt;
   &lt;rowConstraints&gt;
      &lt;RowConstraints /&gt;
   &lt;/rowConstraints&gt;
&lt;/GridPane&gt;

My Main.Java


import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class Main extends Application {

    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource(&quot;sample.fxml&quot;));
        primaryStage.setTitle(&quot;Hello World&quot;);
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


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

And finally the error thats thrown when I try to use the "Add" button and write the form.

	at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
	at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
	at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
	at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
	at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8879)
	at javafx.controls/javafx.scene.control.Button.fire(Button.java:200)
	at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
	at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
	at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
	at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
	at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
	at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3851)
	at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1200(Scene.java:3579)
	at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
	at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2588)
	at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
	at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
	at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
	at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
	at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
	at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
	at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
	at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
	at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:567)
	at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
	at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
	at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
	... 51 more
Caused by: java.lang.NullPointerException
	at java.base/java.io.Writer.write(Writer.java:249)
	at sample.Controller.Add(Controller.java:29)
	... 62 more

Any help is greatly appreciated as I am new to Java.

答案1

得分: 1

根据情况,您的程序似乎从未设置Output的值(可以在方法顶部使用System.out.println(Output)进行确认)。也许您可以考虑将handleButtonAction方法中的所有逻辑放入Add方法中,而不必使用一个字符串来表示Output,具体做法如下:

public void Add(ActionEvent event) {
    try {
        FileWriter fw = new FileWriter("D:/Assignment3&4_Output.txt");
        fw.append("Student Name: " + InputName.getText() + "|| Student Email: " + InputEmail.getText() + "\n");
        fw.close();
        System.out.println("File updated");
    } catch (IOException e) {
        System.out.println("File could not be found. Please check the file path.");
    }
}

或者,您可以将输出字符串的赋值移到add()方法中,具体做法如下:

public void Add(ActionEvent event) {
    output = "Student Name: " + InputName.getText() + "|| Student Email: " + 
        InputEmail.getText() + "\n";
    try {
        FileWriter fw = new FileWriter("D:/Assignment3&4_Output.txt");
        fw.append(output);
        fw.close();
        System.out.println("File updated");
    } catch (IOException e) {
        System.out.println("File could not be found. Please check the file path.");
    }
}

append(String s) 方法是追加而不是覆盖内容的,使用哪个取决于您的需求。close() 方法将流刷新到文件(保存内容)并关闭流。

附注:您应该将除了类以外的所有首字母都改为小写

英文:

By the looks of it your program is never setting the value of Output (confirm with System.out.println(Output) at the top of the method), maybe instead of having a string for Output at all you just put all the logic from the handleButtonAction method in Add like so

public void Add(ActionEvent event) {
        try {
            FileWriter fw = new FileWriter(&quot;D:/Assignment3&amp;4_Output.txt&quot;);
            fw.append(&quot;Student Name: &quot; + InputName.getText() + &quot;|| Student Email: &quot; + InputEmail.getText() + &quot;\n&quot;);
            fw.close();
            System.out.println(&quot;File updated&quot;);
        } catch (IOException e) {
            System.out.println(&quot;File could not be found. Please check the file path.&quot;);


        }
    }

Or move the output string assignment to add()

public void Add(ActionEvent event) {
    output =&quot;Student Name: &quot; + InputName.getText() + &quot;|| Student Email: &quot; + 
    InputEmail.getText() + &quot;\n&quot;
        try {
            FileWriter fw = new FileWriter(&quot;D:/Assignment3&amp;4_Output.txt&quot;);
            fw.append(output);
            fw.close();
            System.out.println(&quot;File updated&quot;);
        } catch (IOException e) {
            System.out.println(&quot;File could not be found. Please check the file path.&quot;);


        }
    }

The append(String s) method adds rather than overwrites, which you use is optional
the close() method flushes the stream into the file (saves it) and closes the stream.

P.S. <a href="https://www.javatpoint.com/java-naming-conventions">You should make the first letter of everything except classes lowercase</a>

huangapple
  • 本文由 发表于 2020年4月10日 02:38:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61127991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定