Изключение за метода за стартиране на приложението, причинено от изключение за зареждане

Опитвам се да създам приложение и докато стартирам, то ми дава грешки по време на изпълнение с този fxml. Опитвам се да създам страница за вход, която скача до началния екран при правилна парола и потребителско име или в противен случай показва грешка. Използвам Scene builder за изгледите и използвам архитектурата Model-View-Controller. Аз съм начинаещ с java-javafx.

Изгледи клас:

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane nodeOrientation="LEFT_TO_RIGHT" prefHeight="720.0" prefWidth="1280.0" style="-fx-background-color: #ffffff;" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="gload.views.main.LoginScreenctrl">
   <children>
      <VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1280.0" style="-fx-background-color: #F3F3F3;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <AnchorPane minHeight="118.0" minWidth="0.0" prefHeight="150.0" prefWidth="1280.0">
               <children>
                  <HBox alignment="TOP_CENTER" layoutX="177.0" layoutY="30.0" prefHeight="90.0" prefWidth="860.0" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="177.0" AnchorPane.rightAnchor="243.0" AnchorPane.topAnchor="30.0">
                     <children>
                        <Text fx:id="gloadtext" fill="#00bbde" fontSmoothingType="LCD" stroke="WHITE" strokeType="OUTSIDE" styleClass="centered" text="GLOAD for" textAlignment="CENTER" wrappingWidth="401.13671875" HBox.hgrow="NEVER">
                           <font>
                              <Font name="Times New Roman Bold" size="68.0" />
                           </font>
                        </Text>
                        <ImageView fitHeight="75.0" fitWidth="417.0" pickOnBounds="true" preserveRatio="true">
                           <image>
                              <Image url="@../../../main/resources/Images/1200px-Logo.svg.png" />
                           </image>
                        </ImageView>
                     </children>
                  </HBox>
               </children>
            </AnchorPane>
            <Separator nodeOrientation="LEFT_TO_RIGHT" prefHeight="23.0" prefWidth="1263.0" />
            <AnchorPane maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="528.0" prefWidth="1280.0" stylesheets="@../../../main/resources/style.css" VBox.vgrow="ALWAYS">
               <children>
                  <VBox alignment="TOP_CENTER" layoutX="275.0" layoutY="21.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="504.0" prefWidth="640.0" style="-fx-background-color: #ffffff;" stylesheets="@../../../main/resources/style.css" AnchorPane.leftAnchor="275.0" AnchorPane.topAnchor="21.0">
                     <children>
                        <ImageView fitHeight="60.0" fitWidth="330.0" pickOnBounds="true" preserveRatio="true">
                           <image>
                              <Image url="@../../../main/resources/Images/1200px-Logo.svg.png" />
                           </image>
                           <VBox.margin>
                              <Insets top="10.0" />
                           </VBox.margin>
                        </ImageView>
                        <Text fill="#22286f" fontSmoothingType="LCD" strokeType="OUTSIDE" strokeWidth="0.0" text="Welcome to ****" textAlignment="CENTER">
                           <font>
                              <Font name="Impact" size="30.0" />
                           </font>
                        </Text>
                        <Text fontSmoothingType="LCD" strokeType="OUTSIDE" strokeWidth="0.0" text="Sign In to Continue" textAlignment="CENTER">
                           <font>
                              <Font name="Impact" size="22.0" />
                           </font>
                        </Text>
                        <AnchorPane prefHeight="344.0" prefWidth="640.0" style="-fx-background-color: #ffffff;">
                           <children>
                              <TextField fx:id="user" layoutX="199.0" layoutY="71.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="28.0" prefWidth="263.0" promptText="Username" AnchorPane.bottomAnchor="240.0" AnchorPane.leftAnchor="199.0" AnchorPane.rightAnchor="178.0" AnchorPane.topAnchor="71.0" />
                              <PasswordField fx:id="password" layoutX="201.0" layoutY="145.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onKeyPressed="#enter" prefHeight="28.0" prefWidth="263.0" promptText="Password" AnchorPane.bottomAnchor="166.0" AnchorPane.leftAnchor="201.0" AnchorPane.rightAnchor="176.0" AnchorPane.topAnchor="145.0" />
                              <Text layoutX="199.0" layoutY="56.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Username:" wrappingWidth="152.291015625" AnchorPane.bottomAnchor="282.1064453125" AnchorPane.leftAnchor="199.0" AnchorPane.rightAnchor="288.708984375" AnchorPane.topAnchor="39.9599609375">
                                 <font>
                                    <Font name="Times New Roman Bold" size="18.0" />
                                 </font>
                              </Text>
                              <Text layoutX="198.0" layoutY="132.0" strokeType="OUTSIDE" strokeWidth="0.0" text="eDir password:" AnchorPane.bottomAnchor="206.1064453125" AnchorPane.leftAnchor="198.0" AnchorPane.rightAnchor="324.5078125" AnchorPane.topAnchor="115.9599609375">
                                 <font>
                                    <Font name="Times New Roman Bold" size="18.0" />
                                 </font>
                              </Text>
                              <ButtonBar layoutX="209.0" layoutY="241.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="37.0" prefWidth="213.0" AnchorPane.bottomAnchor="64.0" AnchorPane.leftAnchor="209.0" AnchorPane.rightAnchor="218.0" AnchorPane.topAnchor="241.0">
                                 <padding>
                                    <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                                 </padding>
                                 <opaqueInsets>
                                    <Insets />
                                 </opaqueInsets>
                                 <buttons>
                                  <Button fx:id="login" lineSpacing="10.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#makeLogin" prefHeight="35.0" prefWidth="197.0" text="Log In">
                                       <padding>
                                          <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                                       </padding>
                                    </Button>
                                 </buttons>
                              </ButtonBar>
                           </children>
                        </AnchorPane>
                     </children>
                     <padding>
                        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
                     </padding>
                     <effect>
                        <DropShadow blurType="GAUSSIAN" />
                     </effect>
                  </VBox>
               </children>
               <VBox.margin>
                  <Insets />
               </VBox.margin>
            </AnchorPane>
         </children>
      </VBox>
   </children>
</AnchorPane>

Модел:

package gload.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Login {


    private String user;

    private String password;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public boolean grantAccess ;


    public boolean login(String usr, String passwd) {
        String username = usr;
        String pass = passwd;
        File userdata = new File("users.txt");//When Clicked on Login
        System.out.println("File Opened");
        try {
            Scanner read = new Scanner(userdata);
            int i=0; // count how many lines in the file
            while(read.hasNextLine()){
                i++;
                //loop through every line in the file and check against the user name & password (Saved in Pairs of lines)
                if(read.nextLine().equals(username)){ // if the same user name
                    System.out.println("Read " + i +  " Line");
                    i++;
                    if(read.nextLine().equals(pass)){ // check password
                        grantAccess = true ; // if also same, change boolean to true
                        System.out.println("Read " + i +  " Line");
                        i++;
                        break; // and break the for-loop
                    }else{
                        grantAccess = false;
                    }
                }
            }
            read.close();
            System.out.println("File Closed");
        }catch (FileNotFoundException e) {

            System.out.println("Error : DATABASE ACCESS ERROR!");

            e.printStackTrace();
        }


        return grantAccess;
    }

}

Контролер:

package gload.controllers;

import gload.model.Login;
import gload.utils.SceneLoader;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


public class LoginScreenctrl implements Initializable {

    private Login model;


    public LoginScreenctrl(){
        this.model = model;
    }

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;


    @FXML
    public TextField user;

    @FXML
    private PasswordField password;


    @FXML
    private Button login;

    public String getUser() {
        return model.getUser();
    }

    public void setUser(String user) {
        model.setUser(user);
    }

    public String getPassword() {
        return model.getPassword();
    }

    public void setPassword(String password) {
        model.setPassword(password);
    }

    public void enter(KeyEvent keyEvent) {                                                  //to login with enter button on password field
        if (keyEvent.getCode().equals(KeyCode.ENTER)) {
            login.fire();
        }
    }

        @FXML
        public void makeLogin(ActionEvent  event) throws IOException {   //This method gets triggered and check the value with the database to grant

            String username = user.getText();
            String pass = password.getText();
            model.login(username , pass);
            if(model.grantAccess = true){
                // let the user continue
                // and do other stuff, for example: move to next window ..etc
                SceneLoader.loadscene("/gload/views/main/welcome.fxml" ,
                        (Stage)((Node) event.getSource()).getScene().getWindow());

            }
            else{
                // return Alert message to notify the deny
                //display error
                Alert dialog = new Alert(Alert.AlertType.ERROR);
                dialog.setTitle("Not able to Login");
                dialog.setHeaderText("Incorrect Username or Password");
                dialog.setContentText("You have entered incorrect username or Password.\nPlease try Again");
                dialog.showAndWait();
            }

    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {


    }




}


Основен клас:

package gload;

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


import java.util.Objects;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("views/main/loginscreen.fxml")));
        primaryStage.setTitle("GLOAD");
        primaryStage.setScene(new Scene(root, 1280, 720));
        primaryStage.show();
    }


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

Проследяване на стека

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1862)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1729)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    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:8889)
    at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
    at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:208)
    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:247)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
    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:3856)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1851)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2584)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
    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:831)
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:78)
    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:1857)
    ... 50 more
Caused by: java.lang.NullPointerException: Cannot invoke "gload.model.Login.login(String, String)" because "this.model" is null
    at gload/gload.controllers.LoginScreenctrl.makeLogin(LoginScreenctrl.java:96)
    ... 61 more


person HJ3008    schedule 04.06.2021    source източник
comment
контролерът трябва да има конструктор без параметри   -  person kleopatra    schedule 04.06.2021
comment
@kleopatra Актуализирах въпроса след предоставеното от вас решение. но все още не може да се изпълни.   -  person HJ3008    schedule 04.06.2021
comment
сега имате различна грешка и тя ви казва какво точно не е наред (последното caused by ) - нищо чудно, тъй като контролерът инициализира своя модел със себе си - това е нула по това време. Изглежда, че трябва да освежите уменията си върху основите на Java :)   -  person kleopatra    schedule 04.06.2021
comment
така или иначе, когато задавате въпрос за отстраняване на грешки, се изисква минимално възпроизводим пример (имайте предвид M! - никой не иска да минава през тонове несвързан код).   -  person kleopatra    schedule 04.06.2021
comment
ааа, разбирам - вашият модел се подобри значително (в сравнение с предишния въпрос stackoverflow.com/questions/67834389/), няма повече възли в него :) Сега научете как да предавате параметри, имате някои връзки за проучване в коментарите към другия въпрос)   -  person kleopatra    schedule 04.06.2021