ROBO_P
ROBO_P

Reputation: 43

JAVA: Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException ERROR

Hello I am new to java language. I keep getting this error

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.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:8411)
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.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$2(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
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)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
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:1769)
... 48 more
Caused by: java.io.FileNotFoundException: Test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at cw3.Controller.loadPressed(Controller.java:48)

So what I try to do is make the java read text file and then use information inside to calculate mean. Here is my code main.java

package cw3;

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

public class Main extends Application{

@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("Calc.fxml"));
    primaryStage.setTitle("TEST");
    primaryStage.setScene(new Scene(root));
    primaryStage.show();
}

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

Controller.java

package cw3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;

//To open the load window
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class Controller {

@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;

@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;

@FXML // fx:id="load"
private Button load; // Value injected by FXMLLoader

@FXML // fx:id="mean"
private TextArea mean; // Value injected by FXMLLoader

@FXML
void loadPressed(ActionEvent event) throws FileNotFoundException, IOException{

 FileChooser myfileChooser = new FileChooser();
 myfileChooser.setTitle("Open..."); 
 File FileDestination = myfileChooser.showOpenDialog(new Stage());
 String filename = FileDestination.getName();

 System.out.print(filename);

 // FileReader reads text files in the default encoding.
 FileReader fileReader = new FileReader(filename);

 // Always wrap FileReader in BufferedReader.
 BufferedReader bufferedReader = new BufferedReader(fileReader);
 String inputFileLine = null;
 double Mean = 0;
 int totalnumber = 0;


 while ((inputFileLine = bufferedReader.readLine()) != null) {
     Mean += Double.valueOf(inputFileLine);
     totalnumber++;
 }
 double showmean = Mean/totalnumber;
 mean.setText(String.valueOf(showmean));
}

@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
    assert load != null : "fx:id=\"load\" was not injected: check your FXML file 'Calc.fxml'.";
    assert mean != null : "fx:id=\"mean\" was not injected: check your FXML file 'Calc.fxml'.";

}
}

Please help me solve this error it is a bit confuse. I get this error after clicking the open button from load window.

P.S. I use scenebuilder app and netbean in order to develop java application. I believe that fxml file does not matter if you want to see fxml file let me know.

Upvotes: 4

Views: 1496

Answers (1)

Slaw
Slaw

Reputation: 46170

The root error is:

Caused by: java.io.FileNotFoundException: Test.txt (The system cannot find the file specified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:195)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileInputStream.<init>(FileInputStream.java:93)
        at java.io.FileReader.<init>(FileReader.java:58)
        at cw3.Controller.loadPressed(Controller.java:48)

Which is saying the file Test.txt does not exist and that the error is being thrown on line 48 of your cw3.Controller class. Check out the What is a stack trace, and how can I use it to debug my application errors? Q&A for more information about stack traces and how to read them.

In your code:

@FXML
void loadPressed(ActionEvent event) throws FileNotFoundException, IOException{

 FileChooser myfileChooser = new FileChooser();
 myfileChooser.setTitle("Open..."); 
 File FileDestination = myfileChooser.showOpenDialog(new Stage());
 String filename = FileDestination.getName();

 System.out.print(filename);

 // FileReader reads text files in the default encoding.
 FileReader fileReader = new FileReader(filename);

 // Always wrap FileReader in BufferedReader.
 BufferedReader bufferedReader = new BufferedReader(fileReader);
 String inputFileLine = null;
 double Mean = 0;
 int totalnumber = 0;


 while ((inputFileLine = bufferedReader.readLine()) != null) {
     Mean += Double.valueOf(inputFileLine);
     totalnumber++;
 }
 double showmean = Mean/totalnumber;
 mean.setText(String.valueOf(showmean));
}

You're passing the result of FileDestination.getName() (by the way, according to Java naming conventions, variable names start with a lowercase letter) to the FileReader constructor. Here's what the documentation of File#getName() says:

Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence [emphasis added]. If the pathname's name sequence is empty, then the empty string is returned.

You need to pass the full path. You could do this via File#getPath() but it'd probably be easier to just use the FileReader#<init>(File) constructor and pass the File object directly. You also need to remember to close the FileReader when done with it; the easiest way to accomplish this is to use the try-with-resources statement. For example:

File chosenFile = ...;
try (BufferedReader br = new BufferedReader(new FileReader(chosenFile)) {
    // read from the BufferedReader
}
// Note: Closing the BufferedReader will close the nested FileReader

Some other notes:

  • You can use the NIO.2 API to open a BufferedReader by converting the File to a Path via File#toPath() and then using Files#newBufferedReader(Path).

    • Also see some of the other available API, such as Files#lines(Path) (don't forget to close the Stream when done with it).
  • Your method is performing I/O work on the JavaFX Application Thread (i.e. the UI thread). You never want to do blocking or otherwise long-running work on the FX thread as that will freeze the UI which is not a good user experience. Consider moving the I/O work to a background thread, then publishing the result back to the FX thread. See Concurrency in JavaFX and the javafx.concurrent package for more information.

  • You need to handle the case where FileChooser#showOpenDialog(Window) returns null. This will happen if the user cancels out of the dialog. Currently your code will simply throw a NullPointerException.

  • Don't pass some random, just-instantiated Stage to #showOpenDialog(Window). You should pass the appropriate window instance (typically the window the button/whatever belongs to) so that the modality functions correctly (i.e. prevent the user from interacting with the owner window while the file chooser dialog is showing). Each Node holds a reference to its Scene which holds a reference to its Window. In your case, you could use load.getScene().getWindow().

Upvotes: 2

Related Questions