B2 · Episode 8 · 5:15
Building Graphical Interfaces with JavaFX
This episode explains how to build graphical user interfaces using JavaFX, focusing on the Model-View-Controller (MVC) architecture: how the view handles UI elements, the controller manages interactions and updates, and the model encapsulates core logic (e.g., a counter), all working together seamlessly.
Source:Nicolas Hurtubise / classe.iro.umontreal.ca · License:CC BY-SA 4.0
Transcript
qui vous permet de jouer à toutes sortes de jeux de cartes
that lets you play all kinds of card games
dans le fond la logique de la disposition des cartes ici va changer selon le jeu la
Essentially, the logic behind how cards are arranged changes depending on the game
façon les cartes sont disposées puis la façon dont on
— specifically, how the cards are laid out
gagne une partie de cartes
and how a round is won or lost
Mais essentiellement, peu importe le jeu que vous choisissez,
But no matter which game you choose
il y a une logique commune.
there’s a shared underlying logic
Peu importe le jeu que vous choisissez,
No matter which game you choose
vous devriez toujours être capable d'afficher ce petit menu- là qui vous permet de
you should always be able to open this small menu
créer une nouvelle partie, recommencer la partie, choisir un autre jeu,
to start a new game, restart the current one, or switch to another game
annuler, recommencer.
or undo and redo actions
Puis tout ce qui change dans le fond, c'est la disposition des cartes,
What actually changes is only how the cards are arranged
puis la façon de détecter si on a gagné ou si on a perdu.
and how victory or defeat is detected
Dans le fond, il y a toute la vue ici,
In fact, most of this interface here
la grosse majorité de la vue ici va être réutilisée d'un jeu à l'autre,
is reused across different games
ce qui veut dire que vraiment si on écrit chacun des jeux cartes comme étant un
That means if we build each card game as a separate module
modèle séparé, tout ce qui nous reste à faire c'est de brancher ça dans
we just need to plug it into this main program
ce programme- là, puis dans
and into
le fond on a toute la partie de la vue qui est déjà faite.
the underlying view layer, which is already built
quand on veut rajouter un nouveau jeu de cartes.
when we want to add a new card game
Ok, on va regarder un exemple un petit peu plus concret en JavaFX.
OK, let’s look at a more concrete example in JavaFX
Donc il y a le fichier MVC.
Here is the MVC project file
zip qui devrait être disponible sur Studium.
which should be available for download on Studium
On va aller regarder un petit programme qui permet d'entrer des nombres.
We’ll examine a small program that lets users enter numbers
Donc c'est ici le programme qu'on va avoir.
This is the program we’ll run
Puis quand on clique sur ajouter dans le fond, ça va ajouter ça à un compteur,
When you click ‘Add’, the number gets added to a counter
puis le résultat va s'afficher ici.
and the result appears here
Fait que allons regarder ça,
So, let's take a look at this,
allons regarder ça ici.
let's examine it here.
Comment est- ce qu'on peut faire ça?
How can we implement this?
Bien, on va vouloir une classe qui extende application
Well, we’ll need a class that extends Application,
et qui nous permet de simplement définir les éléments graphiques qu'on veut
one that lets us simply define the graphical elements we want to use.
utiliser. Dans la méthode start ici, bien on va lui définir nos
In the start method here, we’ll define our components for the title and the area where we’ll enter numbers,
composantes pour le titre, pour la zone où on va rentrer nos nombres.
the 'Add' button, and the output — i.e., what we want to display — and make it look nice.
le bouton pour ajouter,
the 'Add' button,
la sortie donc qu'est ce qu'on veut afficher, on va aller rendre ça joli.
the output — i.e., what we want to display — and make it look nice.
On va aller définir un événement qui peut se produire quand on clique sur le bouton,
We’ll define an event that triggers when the button is clicked,
puis dans le fond, ça va être le gros de notre classe Vue.
and essentially, that’s the core of our Vue class.
Notre classe Vue va avoir une fonction update_output qu'on peut appeler et qui va
Our Vue class will have an update_output function that we can call,
permettre de modifier le texte qui est affiché dedans.
to update the text displayed inside.
Donc si je lance ce programme- là.
Now, if I run this program,
On va regarder ce qui se passe.
let’s see what happens.
Si je lance ce programme- là, je vais avoir mon super compteur,
running it gives me my super counter,
je peux rentrer des nombres, puis quand je clique sur ajouter ici,
I can enter numbers, then click 'Add' here,
l'événement qui se produit c'est celui- là ici.
and the event that fires is this one here.
C'est simplement d'aller avertir le contrôleur qu'on veut ajouter un nombre à
It simply notifies the controller that
partir de la valeur qui est dans
we want to add a number based on the value in
cet input- là.
this input field.
Donc cet input- là, on peut aller chercher la valeur qui est ici avec cette
For this input field, we can retrieve its value using this function,
fonction- là. Puis dans le fond, voilà,
and essentially, that’s it:
le contrôleur écrit dans la vue directement, le contrôleur écrit ici.
the controller writes directly into the view — right here.
Au moment d'instancier le contrôleur,
When instantiating the controller,
on lui passe en paramètre une référence à l'instance de vue qu'on a en ce moment.
we pass it, as a parameter, a reference to the current view instance.
Puis à ce moment- là,
Then, at that moment,
cette instance- là va pouvoir être référencée dans l'autre sens.
this instance can be referenced in the opposite direction.
Si on va regarder au niveau du contrôleur, qu'est- ce qui se passe?
If we look at the controller level, what happens?
Le contrôleur, au moment de le créer,
When the controller is created,
va simplement garder une référence à la vue pour pouvoir aller demander à la vue de
it simply keeps a reference to the view, so it can ask the view to
modifier ce qui est affiché.
update what is displayed.
Puis le contrôleur va aller créer le modèle.
Then, the controller will create the model.
Donc le contrôleur va aller créer le modèle,
So the controller creates the model—
le modèle qui est simplement un compteur, donc un compteur qui
a model that is simply a counter,
possède une fonction ajouter, donc on peut rajouter quelque chose,
which has an 'add' function, allowing us to add values,
puis on peut aller chercher la valeur totale avec tout ce qui a été ajouté.
and then retrieve the total sum of all added values.
Donc ici c'est vraiment le modèle de l'application,
So here, this model is truly the application's core model,
c'est le problème abstrait qui est essentiellement de compter,
the abstract problem at its heart: counting,
de rajouter des nombres, compter.
adding numbers and accumulating them.
C'est quelque chose qui peut clairement exister sans interface graphique,
It can clearly exist without any graphical interface,
c'est quelque chose qu'on pourrait intégrer dans un autre projet,
it could be integrated into another project,
c'est quelque chose où on pourrait faire une interface textuelle à ça.
or we could build a text-based interface for it.
Fait que le contrôleur ici va aller garder une référence à la vue,
So the controller keeps a reference to the view,
va aller créer le modèle, puis va commencer par aller mettre à jour la vue en lui
creates the model, and then starts by updating the view,
demandant d'utiliser la valeur du modèle comme output.
asking it to use the model’s current value as its output.
quand on clique sur le bouton
When the user clicks the button,
pour rajouter un nombre dans notre
to add a number in our view,
vue ça appelle la fonction du contrôleur avec le texte qui correspond au nombre
the corresponding controller function is called, passing in the text representing that number,
qu'on veut rajouter.
i.e., the number we want to add.
Cette fonction- là dans le fond
This function essentially will,
va aller lire ce qui a été rentré,
read what was entered,
va demander au modèle de rajouter ce nombre- là,
ask the model to add that number,
puis va demander à la vue de se mettre
and then ask the view to update itself accordingly,
à jour en conséquence.
completing the entire process.
On fait un try catch ici parce que quand on essaie de valider
We use a try-catch here because when we try to validate the input,
l'entrée, dans le fond quand on essaie de lire le texte comme étant un double,
we’re essentially trying to read the text as a double,
peut- être que les utilisateurs ont écrit n'importe quoi, puis à ce moment- là,
and users might have entered anything at all—so at that point,
le modèle peut pas fonctionner avec ça.
the model can’t work with that.
Ce qui va se passer, c'est qu'on va, au moment du catch, dans le fond,
What will happen is that, when the catch block runs,
quand on se rend compte qu'il y a eu une erreur, on
i.e., the moment we detect an error,
va aller réinitialiser le modèle à zéro,
we’ll reset the model to its initial state,
puis on va aller afficher dans la vue erreur.
and then display an error message in the view.