JavaFX应用程序:线程“JavaFX Application Thread”中的异常java.lang.RuntimeException:java.lang.reflect.InvocationTargetException [duplicate]

时间:2022-04-02 17:04:00

This question already has an answer here:

这个问题在这里已有答案:

I'm working on JavaFX and SQL project. First of all login window opens and if the username and password matches to one stored in my databases then AddCustomer deatils windows will pop up[Works fine till here] . A table would be in my database for the user entry. But as I click on 'save' button I get an error like this

我正在研究JavaFX和SQL项目。首先打开登录窗口,如果用户名和密码与我的数据库中存储的用户名和密码匹配,则会弹出AddCustomer deatils windows [直到这里工作正常]。一个表将在我的数据库中用于用户输入。但是当我点击“保存”按钮时,我收到这样的错误

   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$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)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(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.lang.NullPointerException
    at sample.MysqlConnector.<init>(MysqlConnector.java:22)
    at sample.AddCustomer.addcustomer(AddCustomer.java:52)
    ... 58 more

My Main.java

package sample;

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

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("login1.fxml"));
            primaryStage.setTitle("NOVOTEL HOTEL ");
            primaryStage.setScene(new Scene(root, 500, 475));
            primaryStage.show();
        }
        catch(Exception e )
        {
            e.printStackTrace();
        }
    }


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

My MysqlConnector.java

package sample;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import javafx.fxml.FXML;

import java.sql.*;


public class MysqlConnector {
    @FXML
    public static Statement stmt;
    @FXML
    public static Connection conn;




    public MysqlConnector() {
        Connector();
        String TableName = "CustomerDetails";
        try {
            stmt = conn.createStatement();
            DatabaseMetaData dbm = conn.getMetaData();
            ResultSet tables = dbm.getTables(null, null, TableName.toUpperCase(), null);
            if (tables.next()) {
                System.out.println("Ready to go");

            } else {
                stmt.execute("CREARE TABLE " + TableName + "("
                        + " customername varchar(45) primary key,"
                        + " customername int" +
                        "+ customernumber int" +
                        "+  customerstay int" +
                        "+  customerguests varchar(45)"
                        + ")");
            }
        } catch (SQLException e1) {
            System.err.println(e1.getMessage());
        }
    }

    @Nullable
    @NotNull
    public static Connection Connector() {


        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "password");
            return conn;
        } catch (Exception e) {
            return null;
        }

    }
    @NotNull
    @Nullable
    public  static ResultSet executeQuery(String query) {

        ResultSet result ;

        try {
             stmt = conn.createStatement();
            result=stmt.executeQuery(query);



        } catch (SQLException e) {
            System.out.println("Error here");
            e.printStackTrace();
            return null;

        }
        return result;
    }
    @NotNull
    @Nullable
    public boolean executeAction(String qu) {
        try {
            stmt = conn.createStatement();
            stmt.execute(qu);
            return true;


        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}

My LoginModel.java

package sample;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import javafx.fxml.FXML;

import java.sql.*;


public class MysqlConnector {
    @FXML
    public static Statement stmt;
    @FXML
    public static Connection conn;




    public MysqlConnector() {
        String TableName = "CustomerDetails";
        try {
            stmt = conn.createStatement();
            DatabaseMetaData dbm = conn.getMetaData();
            ResultSet tables = dbm.getTables(null, null, TableName.toUpperCase(), null);
            if (tables.next()) {
                System.out.println("Ready to go");

            } else {
                stmt.execute("CREARE TABLE " + TableName + "("
                        + " customername varchar(45) primary key,"
                        + " customername int" +
                        "+ customernumber int" +
                        "+  customerstay int" +
                        "+  customerguests varchar(45)"
                        + ")");
            }
        } catch (SQLException e1) {
            System.err.println(e1.getMessage());
        }
    }

    @Nullable
    @NotNull
    public static Connection Connector() {


        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "password");
            return conn;
        } catch (Exception e) {
            return null;
        }

    }
    @NotNull
    @Nullable
    public  static ResultSet executeQuery(String query) {

        ResultSet result ;

        try {
             stmt = conn.createStatement();
            result=stmt.executeQuery(query);



        } catch (SQLException e) {
            System.out.println("Error here");
            e.printStackTrace();
            return null;

        }
        return result;
    }
    @NotNull
    @Nullable
    public boolean executeAction(String qu) {
        try {
            stmt = conn.createStatement();
            stmt.execute(qu);
            return true;


        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}

My Controller class

我的Controller类

import com.sun.istack.internal.Nullable;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.*;
public class Controller  implements Initializable {
    @NotNull
    @Nullable
    public LoginModel loginModel = new LoginModel();
    @FXML

    private Label isConnected,db;
    @FXML
    private TextField txtUsername;
    @FXML
    private TextField txtpassword;

    @FXML
    Button abutton = new Button("Login");

    private AddCustomer  addCustomer;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        if (loginModel.isDBConnected()) {
            db.setText("Connected to DATABASE");
        } else {
            db.setText("Not Connected");
        }
    }

    public void Login (ActionEvent event ) {
        try {
            if (loginModel.isLogin(txtUsername.getText(), txtpassword.getText())) {
                isConnected.setText("Correct");
                try {
                    FXMLLoader addCustomer= new FXMLLoader(getClass().getResource("/sample/addcustomer.fxml"));
                    Parent root1 = (Parent)addCustomer.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root1));
                    stage.setTitle("ENTRY RECORD");
                    stage.show();
                }
                catch (Exception e){
                    e.printStackTrace();
                }

            } else {
                Alert alert=new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("YOU ARE NOT AUTHENTICATED");
                alert.show();


            }
        } catch (SQLException e) {

            isConnected.setText("Incorrect");
            e.printStackTrace();
        }
    }


}

FXML of COntroller Class

COntroller类的FXML

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane prefHeight="335.0" prefWidth="526.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Label id="isConnected" fx:id="isConnected" layoutX="69.0" layoutY="27.0" prefHeight="45.0" prefWidth="165.0" textAlignment="CENTER" textFill="#e81313">
         <font>
            <Font size="15.0" />
         </font></Label>
      <TextField fx:id="txtUsername" accessibleRole="MENU" layoutX="152.0" layoutY="124.0" promptText="Username" />
      <Button fx:id="abutton" layoutX="201.0" layoutY="227.0" mnemonicParsing="false" onAction="#Login" text="Login" />
      <PasswordField fx:id="txtpassword" layoutX="152.0" layoutY="154.0" promptText="Password" />
      <Label fx:id="db" layoutX="247.0" layoutY="41.0" text="status">
         <font>
            <Font size="15.0" />
         </font>
      </Label>
   </children>
</AnchorPane>

My AddCustomer class Here I haven't add functionality for cancel button yet, just want to check 'save' button first.

我的AddCustomer类在这里我还没有添加取消按钮的功能,只想先检查“保存”按钮。

package sample;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

public   class AddCustomer {
    @FXML
    public TextField number;
    @FXML
    public TextField name;
    @FXML
    public TextField stay;
    @FXML
    public TextField noofguests;
    @FXML
    public Button savebutton;
    @FXML
    public Button cancelbutton;
    @FXML
    @NotNull
    @Nullable
    public  void addcustomer(ActionEvent actionEvent) throws Exception {


            String customername = name.getText();
            String customernumber = number.getText();
            String customerstay = stay.getText();
            String customerguests = noofguests.getText();
            if (customername.isEmpty() || customerguests.isEmpty() || customernumber.isEmpty() || customerstay.isEmpty()) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("PLEASE ENTER ALL THE FIELDS");
                alert.show();
                return;

            }

            String qu = "INSERT INTO CustomerDetails VALUES(" + "'" + customername + "'," +
                    "'" + customernumber + "'," +
                    "'" + customerstay + "'," +
                    "'" + customerguests + "'" + ")";
            System.out.println(qu);

        @NotNull
        @Nullable
        MysqlConnector mysqlConnector=new MysqlConnector();
        try {

            if (mysqlConnector.executeAction(qu)) {
                @NotNull
                @Nullable
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText(null);
                alert.setContentText("SUCCESS");
                alert.show();
            } else {
                @NotNull
                @Nullable
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("FAILED");
                alert.show();
            }
        }
        catch(Exception e)
        { e.printStackTrace();}

    }
    public void cancel(ActionEvent actionEvent) {
    }
}

My Add Customer FXML

我的添加客户FXML

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

<?import java.lang.*?>
<?import java.util.*?>


<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="599.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.AddCustomer">
    <children>
        <VBox layoutX="44.0" prefHeight="400.0" prefWidth="513.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="44.0" AnchorPane.rightAnchor="43.0" AnchorPane.topAnchor="0.0">
            <children>
                <TextField fx:id="name" prefHeight="50.0" prefWidth="492.0" promptText="Customer Name">
                    <VBox.margin>
                        <Insets bottom="10.0" left="10.0" right="10.0" top="30.0" />
                    </VBox.margin>
                </TextField>
                <TextField fx:id="number" layoutX="10.0" layoutY="10.0" prefHeight="53.0" prefWidth="492.0" promptText="Customer Number">
                    <VBox.margin>
                        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </TextField>
                <TextField fx:id="stay" layoutX="10.0" layoutY="10.0" prefHeight="52.0" prefWidth="492.0" promptText="Stay Period ">
                    <VBox.margin>
                        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </TextField>
                <TextField fx:id="noofguests" layoutX="10.0" layoutY="35.0" prefHeight="50.0" prefWidth="492.0" promptText="No. Of Guests">
                    <VBox.margin>
                        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </TextField>
                <Button fx:id="savebutton" mnemonicParsing="false" onAction="#addcustomer" prefHeight="47.0" prefWidth="109.0" text="Save">
                    <VBox.margin>
                        <Insets bottom="10.0" left="100.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </Button>
                <Button fx:id="cancelbutton" mnemonicParsing="false" onAction="#cancel" prefHeight="46.0" prefWidth="110.0" text="Cancel">
                    <VBox.margin>
                        <Insets bottom="10.0" left="300.0" right="10.0" top="-57.0" />
                    </VBox.margin>
                </Button>
            </children>
        </VBox>
    </children>
</AnchorPane>

Please help in getting this error fixed.

请帮助修复此错误。

1 个解决方案

#1


1  

The reason you're getting this error is because you're trying to call conn.createStatement(); on conn which is never initialized and therefore null.

你得到这个错误的原因是因为你试图调用conn.createStatement();在conn上,它从未被初始化,因此为null。

I see you have a function called Connector() which will initialize the variable conn but you are never calling it, a fix would be to call Connector() inside the constructor of MysqlConnector before you're trying to do anything with the variable conn.

我看到你有一个名为Connector()的函数,它将初始化变量conn,但你永远不会调用它,修复就是在你尝试用变量conn做任何事情之前调用MysqlConnector构造函数内的Connector()。

public MysqlConnector() {
   conn = Connector();

   if (conn != null) {
      // Do your things here
   }

}

#1


1  

The reason you're getting this error is because you're trying to call conn.createStatement(); on conn which is never initialized and therefore null.

你得到这个错误的原因是因为你试图调用conn.createStatement();在conn上,它从未被初始化,因此为null。

I see you have a function called Connector() which will initialize the variable conn but you are never calling it, a fix would be to call Connector() inside the constructor of MysqlConnector before you're trying to do anything with the variable conn.

我看到你有一个名为Connector()的函数,它将初始化变量conn,但你永远不会调用它,修复就是在你尝试用变量conn做任何事情之前调用MysqlConnector构造函数内的Connector()。

public MysqlConnector() {
   conn = Connector();

   if (conn != null) {
      // Do your things here
   }

}