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 :

Actualier ma scene javaFX en fonction du changement d'un StringProperty


Sujet :

JavaFX

  1. #1
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Mars 2019
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 26
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2019
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Actualier ma scene javaFX en fonction du changement d'un StringProperty
    Bonsoir bonsoir (ou bonjour !)

    Je début en java et je dois faire un jeu (projet pour un de mes cours), j'ai quelques bases en POO, seulement voilà : j'ai du mal avec les interfaces graphiques, surtout à faire le lien entre action - mise à jour de l'interface (utilisation de listeners, ou de biding (que je n'ai jamais utilisé ))

    En gros, j'ai une scène javaFX (c'est un JFXPanel, dans swing) d'une part (dans une classe Vue) et un joueur d'autre part, le joueur est une instance de la classe Player et il est utilisé dans ma classe Game. En gros, les joueurs jouent tour à tour, et j'aimerais afficher dans ma scène FX le nom du joueur actuel (currentPlayer) : j'arrive bien à gérer la partie code du jeu, mais je n'arrive pas à faire en sorte que le nom change bel et bien dans ma scène....

    Le nom du joueur est en fait un SimpleStringProperty, et j'utilise setValue(String n) pour définir son nom. J'ai essayé d'utiliser des listeners trouvés sur le net, mais ça ne fonctionne pas....

    Voilà à quoi ressemble mon code (il y a les 3 classes) :

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
     
    public class TestView {
    	protected static Game game = new Game("Random Game");
    	protected static BorderPane root = new BorderPane();
    	protected static GridPane grilleHaut = new GridPane();
     
    	public static void main(String[] args) throws InterruptedException {
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				TestView.initialisation();
    			}
    		});
    		game.runSomething();
    	}
     
    	public static void initialisation() {
    		JFrame mainSwingFrame = new JFrame("Game");
    		JFXPanel mainFXFrame = new JFXPanel();
    		mainSwingFrame.add(mainFXFrame);
    		mainSwingFrame.setSize(1200, 900);
    		mainSwingFrame.setVisible(true);
    		mainSwingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		Platform.runLater(new Runnable() {
    			public void run() { initFX(mainFXFrame);}
    		}  );
    	}
     
    	public static void initFX(JFXPanel frameFX) {
    		Scene scene = newScene();
    		frameFX.setScene(scene);
    	}
     
    	public static Scene newScene() {
    		Scene scene = new Scene(root, Color.LIGHTGOLDENRODYELLOW);
     
    		Text gameName = new Text(game.name);
    		grilleHaut.add(gameName, 0, 0);
    		GridPane.setConstraints(gameName, 0, 0, 1, 1, HPos.CENTER, VPos.TOP);
     
    		Text turn = new Text("It's " + game.currentPlayer.getName() + "'s turn to play.");
    		game.currentPlayer.name.addListener((observable, oldValue, newValue) -> {
    			turn.setText("C'est au tour de : " + newValue);
    		});
    		game.currentPlayer.name.addListener(new ChangeListener<String>() {
                public void changed(ObservableValue<? extends String> o,String oldv,String newv) {
                	turn.setText("It's time to play for : " + newv);
                	System.out.println("accessed on TestView.");
                }
            });
     
    		grilleHaut.add(turn, 0, 1);
    		GridPane.setConstraints(turn, 0, 1, 1, 1, HPos.CENTER, VPos.CENTER);
    		BorderPane.setAlignment(grilleHaut, Pos.TOP_RIGHT);
    		root.setTop(grilleHaut);
     
    		return(scene);
    	}
     
    }
     
    //GAME CLASS ==============
    //=========================
    class Game {
    	String name;
    	Player p1 = new Player("Person 1");
    	Player p2 = new Player("Human 2");
    	Player currentPlayer;
     
    	public Game(String n) {
    		name=n;
    		currentPlayer = p1;
    	}
     
    	public void runSomething() {
    		//here goes code to run a game
    		System.out.println(currentPlayer.getName());
    		currentPlayer = p2; //at some point in the game, it's p2's time to play
    		String pressToContinue; Scanner ptc = new Scanner(System.in); pressToContinue = ptc.nextLine();
    		System.out.println(currentPlayer.getName());
    		currentPlayer = p1; //and then p1's again
    		String pressToContinue2; Scanner ptc2 = new Scanner(System.in); pressToContinue2 = ptc.nextLine();
    		System.out.println(currentPlayer.getName());
    	}
    }
     
     
    //PLAYER CLASS ==============
    //===========================
    class Player {
    	protected StringProperty name = new SimpleStringProperty();
    	public Player(String n) { 
    		name.setValue(n); 
    		name.addListener(new ChangeListener<String>() {
                public void changed(ObservableValue<? extends String> o,String oldv,String newv) {
                	Text turn = new Text("It's time to play for : " + newv);
                	TestView.grilleHaut.add(turn, 0, 1);
                	System.out.println("accessed on Player.");
                }
            });}
    	public String getName() { return name.getValue(); }
    }
    Je prends toute suggestion ou explication. Merci beaucoup !! Et désolée si mes questions vous semblent stupides, je débute vraiment en interfaces graphiques...

  2. #2
    Rédacteur/Modérateur

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

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Hum c'est quoi exactement ton soucis ? Là je peine à comprendre ce qu'on doit saisir sur la console et où tu dois voir le nom du joueur s'afficher sur l'écran.

    A un moment tu fais un game.currentPlayer.name.addListener() mais ce listener est uniquement ajouté sur l'objet qui était à ce moment là référencé par currentPlayer la prochaine fois que tu changes la valeur de currentPlayer et que tu changes son nom ben le listener n'est jamais invoqué car ce n'est pas le même objet.

    C'est un truc comme ça que tu cherches à faire ?

    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
    package test;
     
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.text.Text;
     
    //PLAYER CLASS ==============
    //===========================
    public class Player {
     
        private StringProperty name = new SimpleStringProperty();
     
        public Player(String n) {
            name.setValue(n);
            name.addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> o, String oldv, String newv) {
                    Text turn = new Text("It's time to play for : " + newv);
                    TestView.grilleHaut.add(turn, 0, 1);
                    System.out.println("accessed on Player.");
                }
            });
        }
     
        public String getName() {
            return name.getValue();
        }
     
        public StringProperty nameProperty() {
            return name;
        }
    }
    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    package test;
     
    import javafx.application.Platform;
    import javafx.beans.binding.Bindings;
    import javafx.beans.binding.StringBinding;
    import javafx.embed.swing.JFXPanel;
    import javafx.geometry.HPos;
    import javafx.geometry.Pos;
    import javafx.geometry.VPos;
    import javafx.scene.Scene;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.GridPane;
    import javafx.scene.paint.Color;
    import javafx.scene.text.Text;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
     
    public class TestView {
     
        protected static Game game = new Game("Random Game");
        protected static BorderPane root = new BorderPane();
        protected static GridPane grilleHaut = new GridPane();
     
        public static void main(String[] args) throws InterruptedException {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    TestView.initialisation();
                }
            });
            game.runSomething();
        }
     
        public static void initialisation() {
            JFrame mainSwingFrame = new JFrame("Game");
            JFXPanel mainFXFrame = new JFXPanel();
            mainSwingFrame.add(mainFXFrame);
            mainSwingFrame.setSize(1200, 900);
            mainSwingFrame.setVisible(true);
            mainSwingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            Platform.runLater(new Runnable() {
                public void run() {
                    initFX(mainFXFrame);
                }
            });
        }
     
        public static void initFX(JFXPanel frameFX) {
            Scene scene = newScene();
            frameFX.setScene(scene);
        }
     
        public static Scene newScene() {
            Scene scene = new Scene(root, Color.LIGHTGOLDENRODYELLOW);
            Text gameName = new Text(game.name);
            grilleHaut.add(gameName, 0, 0);
            GridPane.setConstraints(gameName, 0, 0, 1, 1, HPos.CENTER, VPos.TOP);
            StringBinding currentPlayerName = Bindings.selectString(game.currentPlayer, "name");        
            StringBinding turnToPlay = new StringBinding() {
                {
                    bind(currentPlayerName);
                }
     
                @Override
                public void dispose() {
                    unbind(currentPlayerName);
                    super.dispose();
                }                        
     
                @Override
                protected String computeValue() {
                    String playerName = currentPlayerName.getValue();
                    String result = (playerName == null) ? null : "It's " + playerName + "'s turn to play.";
                    return result;
                }
            };
            Text turn = new Text();
            turn.textProperty().bind(turnToPlay);
            grilleHaut.add(turn, 0, 1);
            GridPane.setConstraints(turn, 0, 1, 1, 1, HPos.CENTER, VPos.CENTER);
            BorderPane.setAlignment(grilleHaut, Pos.TOP_RIGHT);
            root.setTop(grilleHaut);
     
            return (scene);
        }
    }
    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    package test;
     
    import javafx.application.Platform;
    import javafx.beans.binding.Bindings;
    import javafx.beans.binding.StringBinding;
    import javafx.embed.swing.JFXPanel;
    import javafx.geometry.HPos;
    import javafx.geometry.Pos;
    import javafx.geometry.VPos;
    import javafx.scene.Scene;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.GridPane;
    import javafx.scene.paint.Color;
    import javafx.scene.text.Text;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
     
    public class TestView {
     
        protected static Game game = new Game("Random Game");
        protected static BorderPane root = new BorderPane();
        protected static GridPane grilleHaut = new GridPane();
     
        public static void main(String[] args) throws InterruptedException {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    TestView.initialisation();
                }
            });
            game.runSomething();
        }
     
        public static void initialisation() {
            JFrame mainSwingFrame = new JFrame("Game");
            JFXPanel mainFXFrame = new JFXPanel();
            mainSwingFrame.add(mainFXFrame);
            mainSwingFrame.setSize(1200, 900);
            mainSwingFrame.setVisible(true);
            mainSwingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            Platform.runLater(new Runnable() {
                public void run() {
                    initFX(mainFXFrame);
                }
            });
        }
     
        public static void initFX(JFXPanel frameFX) {
            Scene scene = newScene();
            frameFX.setScene(scene);
        }
     
        public static Scene newScene() {
            Scene scene = new Scene(root, Color.LIGHTGOLDENRODYELLOW);
            Text gameName = new Text(game.name);
            grilleHaut.add(gameName, 0, 0);
            GridPane.setConstraints(gameName, 0, 0, 1, 1, HPos.CENTER, VPos.TOP);
            StringBinding currentPlayerName = Bindings.selectString(game.currentPlayer, "name");        
            StringBinding turnToPlay = new StringBinding() {
                {
                    bind(currentPlayerName);
                }
     
                @Override
                public void dispose() {
                    super.dispose();
                    unbind(currentPlayerName);
                }                        
     
                @Override
                protected String computeValue() {
                    String playerName = currentPlayerName.getValue();
                    String result = (playerName == null) ? null : "It's " + playerName + "'s turn to play.";
                    return result;
                }
            };
            Text turn = new Text();
            turn.textProperty().bind(turnToPlay);
            grilleHaut.add(turn, 0, 1);
            GridPane.setConstraints(turn, 0, 1, 1, 1, HPos.CENTER, VPos.CENTER);
            BorderPane.setAlignment(grilleHaut, Pos.TOP_RIGHT);
            root.setTop(grilleHaut);
     
            return (scene);
        }
    }
    Egalement : était-il vraiment nécessaire de faire une application Swing ? (peut-être que oui en fonction de tes besoins)
    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

Discussions similaires

  1. Bogue avec un composant Swing dans une scene javaFX
    Par Stefounette dans le forum JavaFX
    Réponses: 0
    Dernier message: 06/05/2010, 15h38
  2. Fonction JS - changement background image au clique
    Par Inkone dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 14/03/2010, 11h45
  3. Déclenchement d'une fonction au changement d'un select
    Par camcam8782 dans le forum Général JavaScript
    Réponses: 9
    Dernier message: 30/03/2009, 17h41
  4. Réponses: 4
    Dernier message: 21/01/2009, 08h15
  5. Réponses: 7
    Dernier message: 30/08/2006, 13h33

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