Search code examples
javajavafxfxml

How to fix Null Pointer exceptions


I need help setting the text of the label in my main.view.fxml to the current hour, minute and second as it's throwing a nullpointer exception

What I tried so far:
Calendar calendar = new GregorianCalendar();
HRS_lbl.setText(String.valueOf(calendar.get(Calendar.HOUR)));
MIN_lbl.setText(String.valueOf(calendar.get(Calendar.MINUTE)));
SEC_lbl.setText(String.valueOf(calendar.get(Calendar.SECOND)));

But its not working...

This is my fxml file

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.effect.Blend?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.paint.LinearGradient?>
<?import javafx.scene.paint.Stop?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="209.0" prefWidth="758.0" style="-fx-background-color: #227B89;" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="lecture.application.mainViewController">
   <children>
      <FlowPane orientation="VERTICAL" prefHeight="209.0" prefWidth="273.0" style="-fx-background-color: #1F1F1F;" AnchorPane.leftAnchor="0.0">
         <effect>
            <Blend />
         </effect>
         <children>
            <AnchorPane prefHeight="209.0" prefWidth="276.0">
               <children>
                  <Label layoutX="65.0" layoutY="80.0" text="The Clock">
                     <font>
                        <Font size="34.0" />
                     </font>
                     <textFill>
                        <LinearGradient endX="1.0" endY="1.0">
                           <stops>
                              <Stop color="#e0e3ebcc" />
                              <Stop color="#e0e3ebcc" offset="0.32950191570881227" />
                              <Stop color="WHITE" offset="1.0" />
                           </stops>
                        </LinearGradient>
                     </textFill>
                  </Label>
               </children>
            </AnchorPane>
         </children>
      </FlowPane>
      <Label fx:id="HRS_lbl" layoutX="360.0" layoutY="49.0" text="00">
         <font>
            <Font name="Consolas Bold" size="35.0" />
         </font>
         <padding>
            <Insets left="20.0" top="20.0" />
         </padding>
      </Label>
      <Label fx:id="MIN_lbl" layoutX="453.0" layoutY="49.0" text="00">
         <font>
            <Font name="Consolas Bold" size="35.0" />
         </font>
         <padding>
            <Insets left="20.0" top="20.0" />
         </padding>
      </Label>
      <Label fx:id="SEC_lbl" layoutX="559.0" layoutY="49.0" prefHeight="61.0" prefWidth="82.0" text="00">
         <font>
            <Font name="Consolas Bold" size="35.0" />
         </font>
         <padding>
            <Insets left="20.0" top="20.0" />
         </padding>
      </Label>
      <Label layoutX="390.0" layoutY="123.0" text="HRS" />
      <Label layoutX="483.0" layoutY="117.0" prefHeight="30.0" prefWidth="28.0" text="MIN" />
      <Label layoutX="591.0" layoutY="123.0" text="SEC" />
      <Button fx:id="exit_btn" layoutX="690.0" layoutY="6.0" mnemonicParsing="false" text="Exit" textFill="#000000fa" />
   </children>
   <opaqueInsets>
      <Insets />
   </opaqueInsets>
</AnchorPane>

This is the error it is showing Is this warning critical : WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.161

Apr 23, 2018 10:34:47 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.161
Exception in Application start method
java.lang.NullPointerException
    at lecture.application.mainViewController$1.run(mainViewController.java:39)
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at lecture.application.mainViewController.setTime(mainViewController.java:51)
    at lecture.application.Main.start(Main.java:41)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    ... 1 more

This is the main class

So the error is starting at line 39 where i am starting to setText to the label in my fxml file

private Stage primaryStage;
private AnchorPane mainLayout;
double x;
double y;   

@Override
public void start(Stage primaryStage) throws IOException {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("The Clock ");
    this.primaryStage.setResizable(true);
    this.primaryStage.setMaximized(false);
    this.primaryStage.setAlwaysOnTop(false);
    this.primaryStage.initStyle(StageStyle.UNDECORATED);
    mainViewController controler = new mainViewController();

    primaryStage.maximizedProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue)
            primaryStage.setMaximized(false);
    });
    showMainView();
    controler.setTime();
    setDrag();
}

private void showMainView() throws IOException {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("main.view.fxml"));
        mainLayout = loader.load();

        Scene scene = new Scene(mainLayout);
        primaryStage.setScene(scene);
        primaryStage.show();}

    catch(Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        e.printStackTrace();
    }
}

void setDrag() {     
    mainLayout.setOnMousePressed(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent arg0) {
            x = arg0.getSceneX();
            y = arg0.getSceneY();
        }
    });

    mainLayout.setOnMouseDragged(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            primaryStage.setX(event.getSceneX() - x);
            primaryStage.setY(event.getSceneY() - y);
        }
    });  
}

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

This is the fxml Controller class

@FXML
private Label HRS_lbl;

@FXML
private Label MIN_lbl;

@FXML
private Label SEC_lbl;

@FXML
private Button exit_btn;

void setTime() {
    new Thread () {
        public void run() {
            try {
                Calendar calendar = new GregorianCalendar();
                HRS_lbl.setText(String.valueOf(calendar.get(Calendar.HOUR)));
                MIN_lbl.setText(String.valueOf(calendar.get(Calendar.MINUTE)));
                SEC_lbl.setText(String.valueOf(calendar.get(Calendar.SECOND)));
            } catch (Exception e) {
                e.getMessage();
                e.printStackTrace();
            }
        }
    }.start();

    exit_btn.setOnAction(new javafx.event.EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            JOptionPane.showMessageDialog(null, "Thank you for using The Clock...... developed By Tawanda Mavondo");
        }
    });
}

Solution

  • It's all about your controller

    *You take an object for a controller but it's reference has no relation with your VIEW (FXML)

    you can add whatever you want to do in your controller and use initialize function which start after render view that's mean it will be start immediately .

    @Override
    public void initialize(URL url, ResourceBundle rb) {
            // TODO
    setTime() ;
    }  
    

    I test it it works fine

    Attention:you are using MVC design pattern .