IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaFX Discussion :

NullPointerException inexpliqué avec fichier fxml


Sujet :

JavaFX

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2015
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juin 2015
    Messages : 185
    Par défaut NullPointerException inexpliqué avec fichier fxml
    Bonjour à tous !
    Je viens vers vous aujourd'hui car je galère sur un problème depuis plusieurs jours et ça commence à me rendre fou.

    Je suis en train de programmer un petit jeu. J'ai une première scene construite dans un fichier fxml associé à un fichier controller et ça fonctionne bien, j'arrive à faire "communiquer" le controleur avec le fichier fxml.
    A un moment un bouton lance une méthode (showing() ) d'une nouvelle classe (Indices) qui appelle un nouveau FXMLLoader et donc un nouveau fichier fxml (ça ouvre une nouvelle scene dans une nouvelle fenêtre). Dans ce fichier j'ai défini ma nouvelle classe comme controleur.
    Mais là par contre impossible de faire "communiquer" les deux fichiers. Quand, dans le controleur, je fais référence à un élément du fichier fxml j'ai un nullPointerException.
    Pourtant je m'y suis pris comme avec ma première scene...

    Voici la classe qui ouvre la nouvelle scene dans une nouvelle fenêtre et qui sert de controleur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    package application;
     
    import java.io.IOException;
    import java.net.URL;
    import java.util.ResourceBundle;
     
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.fxml.Initializable;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
     
    public class Indices implements Initializable {
     
    	@FXML	private static Label indix;
     
     
    	public static void showing() throws IOException {
    		final FXMLLoader loader4 = new FXMLLoader(Indices.class.getResource("/ressources/fxml/Indices.fxml"));
    		final Parent root4 = (Parent) loader4.load();
    		final Stage stage4 = new Stage();
    		stage4.setScene(new Scene(root4));
    		stage4.show();
     
     
    		switch (ressources.Variables.etat) {
    		case 2 :
    			indix.setText("Est-ce que ça marche ?");
    		}
    	}
     
     
    	@Override
    	public void initialize(URL arg0, ResourceBundle arg1) {
    		// TODO Auto-generated method stub
    		indix.setText("test");
    	}
    }
    Le fichier fxml :
    Code xml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <?xml version="1.0" encoding="UTF-8"?>
     
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.image.Image?>
    <?import javafx.scene.image.ImageView?>
    <?import javafx.scene.layout.StackPane?>
    <?import javafx.scene.layout.VBox?>
     
    <StackPane prefHeight="421.8" prefWidth="750.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Indices">
       <children>
          <ImageView fitHeight="421.8" fitWidth="750.0" pickOnBounds="true" preserveRatio="true">
             <image>
                <Image url="@../degrade1.png" />
             </image>
          </ImageView>
          <VBox alignment="CENTER">
             <children>
                <Label id="indix" fx:id="indix" text="Label" />
             </children>
          </VBox>
       </children>
    </StackPane>

    et le stackTrace :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    	at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
    	at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
    	at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    	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.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.controls/javafx.scene.control.MenuItem.fire(MenuItem.java:459)
    	at javafx.controls/com.sun.javafx.scene.control.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1380)
    	at javafx.controls/com.sun.javafx.scene.control.ContextMenuContent$MenuItemContainer.lambda$createChildren$12(ContextMenuContent.java:1333)
    	at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    	at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    	at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    	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:3862)
    	at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
    	at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2590)
    	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:830)
    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:62)
    	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:1784)
    	... 42 more
    Caused by: javafx.fxml.LoadException: 
    /D:/Drive/Programmation/EspaceDeTravailPartage2019/com.sarinoty.secondgame/bin/ressources/fxml/Indices.fxml
     
    	at javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    	at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
    	at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    	at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    	at application.Indices.showing(Indices.java:22)
    	at application.Controller.indice(Controller.java:810)
    	... 53 more
    Caused by: java.lang.NullPointerException
    	at application.Indices.initialize(Indices.java:38)
    	at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
    	... 57 more
    Je vous remercie d'avance pour votre aide parce que je deviens fou. Parce que si ça se trouve c'est une broutille, un détails, mais là je ne vois pas...

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 899
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 899
    Billets dans le blog
    54
    Par défaut
    Oui mais tu as déclaré ton label en static et donc il n'est jamais injecté au chargement :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @FXML	private static Label indix;
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  3. #3
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2015
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juin 2015
    Messages : 185
    Par défaut
    Merci Bouye pour ta réponse !

    J'ai été contraint de déclarer le Label en static car pour appeler la méthode showing() j'ai du la déclarer en static. Du coup Eclipse m'a renvoyé une erreur quand j'ai voulu travailler sur le Label : cannot make a reference to a non-static field from a static method (ou un truc du genre).

    Du coup j'ai placé les instructions pour ouvrir la nouvelle fenêtre en lieu et place de l'appel de la méthode showing(). Ainsi plus besoin de "static" dans le controleur et effectivement, ça fonctionne.

    Encore merci bouye !

  4. #4
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2015
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juin 2015
    Messages : 185
    Par défaut
    Bon en fait je retombe sur le même problème alors que ce coup-ci je n'ai aucune variable en static.

    Voici le code du controleur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    package application;
     
    import java.io.IOException;
    import java.net.URL;
    import java.util.ResourceBundle;
     
    import javafx.application.Application;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.fxml.Initializable;
    import javafx.stage.Stage;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.VBox;
     
    public class Main extends Application implements Initializable {
     
    	@FXML	private VBox vboite;
    	@FXML	private ImageView logo;
    	@FXML	private Label presente, titre;
     
    	@Override
    	public void start(Stage primaryStage) throws Exception {
    		Parent root = FXMLLoader.load(getClass().getResource("/ressources/fxml/Intro1.fxml"));
    		primaryStage.setTitle("Nouveau Jeu");
    		Scene scene = new Scene(root);
    		scene.getStylesheets().add(getClass().getResource("/ressources/css/application.css").toExternalForm());
    		scene.getStylesheets().add("https://fonts.googleapis.com/css?family=Caveat");
    		scene.getStylesheets().add("https://fonts.googleapis.com/css?family=Caveat:700");
    		primaryStage.setScene(scene);
    		primaryStage.setResizable(true);
    		primaryStage.setFullScreen(true);
    		primaryStage.show();
     
                    logo.setVisible(false);
    		presente.setVisible(false);
    		titre.setVisible(true);
     
    	}
     
    	public static void main(String[] args) {
    		launch(args);
    	}
     
    	@Override
    	public void initialize(URL arg0, ResourceBundle arg1) {
    		// TODO Auto-generated method stub
     
    	}	
    }
    Dès que je fais référence au premier élément (logo.setVisible(false); à la ligne 37) j'ai un nullPointerException.

    Pourtant les fx:id sont bien présents dans mon fichier fxml :
    Code xml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?xml version="1.0" encoding="UTF-8"?>
     
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.image.Image?>
    <?import javafx.scene.image.ImageView?>
    <?import javafx.scene.layout.StackPane?>
    <?import javafx.scene.layout.VBox?>
    <?import javafx.scene.text.Font?>
     
    <StackPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="1080.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Main">
       <children>
          <ImageView fitHeight="1080.0" fitWidth="1920.0" pickOnBounds="true" preserveRatio="true">
             <image>
                <Image url="@../redforest.png" />
             </image>
          </ImageView>
          <VBox fx:id="vboite" alignment="CENTER" prefHeight="200.0" prefWidth="100.0">
             <children>
                <ImageView id="logo" fx:id="logo" fitHeight="500.0" fitWidth="889.0" pickOnBounds="true" preserveRatio="true">
                   <image>
                      <Image url="@../sarilogobiggris.png" />
                   </image>
                </ImageView>
                <Label fx:id="presente" text="présente :" textFill="#c6c6c6">
                   <font>
                      <Font name="Calibri Bold Italic" size="64.0" />
                   </font>
                </Label>
             </children>
          </VBox>
          <Label fx:id="titre" alignment="CENTER" prefHeight="675.0" prefWidth="1200.0" text="Label" textAlignment="CENTER" visible="false" />
       </children>
    </StackPane>

    ça me rend ouf...

  5. #5
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 899
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 899
    Billets dans le blog
    54
    Par défaut
    Et tu te rends compte qu'en faisant ainsi tu as 2 instances de ton contrôleur ?
    • Cette qui est lancée en tant qu'application et où toutes les variables sont non injectées et donc null
    • Et celle qui a été créée par le loader
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  6. #6
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2015
    Messages
    185
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juin 2015
    Messages : 185
    Par défaut
    Ah non, désolé.
    Je ne vois pas comment je peux avoir deux instances du contrôleur. Ou plutôt je ne vois que celle créé par le loader.
    Je suis un peu paumé là...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. custom Node avec fichier FXML
    Par miltone dans le forum JavaFX
    Réponses: 9
    Dernier message: 27/05/2015, 23h07
  2. Erreur avec fichier .manifest
    Par engi dans le forum Windows
    Réponses: 2
    Dernier message: 16/11/2004, 14h58
  3. [Eclipe 2.1.1]Projet avec fichiers sources existants
    Par mfofana dans le forum Eclipse Java
    Réponses: 1
    Dernier message: 26/02/2004, 05h20
  4. Problème avec fichier texte
    Par jpdelx dans le forum ASP
    Réponses: 7
    Dernier message: 13/11/2003, 13h17
  5. Réponses: 4
    Dernier message: 25/08/2003, 09h02

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo