JavaFX Application:线程“ JavaFX Application Thread”中的异常java.lang.RuntimeException:java.lang.reflect.InvocationTargetException

时间:2018-10-21 07:54:45

标签: java javafx

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

   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

我的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;
        }
    }
}

我的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;
        }
    }
}

我的控制器类

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();
        }
    }


}

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>

我的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) {
    }
}

我的添加客户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>

请帮助解决此错误。

1 个答案:

答案 0 :(得分:1)

出现此错误的原因是,您尝试在从未初始化的conn.createStatement();上调用conn上的null

我看到您有一个名为Connector()的函数,它将初始化变量conn,但您从未调用过,一种解决方法是在{{1 }},然后再尝试对变量Connector()进行任何操作。

MysqlConnector