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 :

Créer un slider avec des labels Strings


Sujet :

JavaFX

  1. #1
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut Créer un slider avec des labels Strings
    Bonjour,

    Je souhaite créer un Slider dont les valeurs et labels correspondraient à des énumérations.

    Dans mon cas, je développe un outil pour l'école de musique de mon village et, pour le niveau des élèves que l'on édite, je souhaite que l'on puisse ajuster le niveau avec un slider.
    Il y a plusieurs niveaux : Eveil, débutant, élémentaire, intermédiaire et avancé.

    voici l'Enum que j'ai faite :
    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
    public enum Niveaux {
    	EVEIL(0, "Eveil"),
    	DEBUTANT(1, "Débutant"),
    	ELEMENTAIRE(2, "Elémentaire"),
    	INTERMEDIAIRE(3, "Intermédiaire"),
    	AVANCE(4, "Avancé");
     
    	private String strNiveau;
     
    	private int intNiveau;
     
    	private Niveaux(int intNiveau_, String strNiveau_){
    		this.strNiveau = strNiveau_;
    		this.intNiveau = intNiveau_;
    	}
     
    	public String getStrNiveau() {return strNiveau;}
    	public int getIntNiveau() {return intNiveau;}
    }
    J'ai créé des énums avec un attribut int et un String. L'int servira à la valeur du slider et la String servira aux labels du slider.

    voici la classe Eleve qui hérite de Personne :
    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
    public class Eleve extends Personne {
     
    	//ATTRIBUTS
    	private ObjectProperty<Niveaux> niveau;
    	private BooleanProperty cotisationPayee;
     
    	//CONSTRUCTORS
    	public Eleve() {
    		super();
    		this.setNiveau(Niveaux.EVEIL);
    		this.setCotisationPayee(true);
    	}
    	public Eleve(String nom_, String prenom_, String adresse_, LocalDate date_naissance_, String telephone1_,
    			String telephone2_, String email1_, String email2_, int anciennete_, List<String> instruments_) {
    		super(nom_, prenom_, adresse_, date_naissance_, telephone1_, telephone2_, email1_, email2_, anciennete_, instruments_);
    	}
    	public Eleve(String nom_, String prenom_, String adresse_, LocalDate date_naissance_, String telephone1_,
    			String telephone2_, String email1_, String email2_, int anciennete_, List<String> instruments_,
    			Niveaux niveau_, boolean cotisationPayee_) {
    		super(nom_, prenom_, adresse_, date_naissance_, telephone1_, telephone2_, email1_, email2_, anciennete_, instruments_);
    //		super(nom_, prenom_, "adresse_", LocalDate.of(1999, 2, 21), "telephone1_", "telephone2_", "email1_", "email2_", 5, instruments_);
     
    		this.setNiveau(niveau_);
    		this.cotisationPayee = new SimpleBooleanProperty(cotisationPayee_);
    	}
     
    	//ACCESSORS
     
    	public boolean getCotisationPayee() {return cotisationPayee.get();}
    	public void setCotisationPayee(boolean cotisationPayee_) {this.cotisationPayee.set(cotisationPayee_);}
    	public BooleanProperty cotisationPayeeProperty(){return cotisationPayee;}
    	public String toStringCotisationPayee() {
    		String strCotis = new String();
    		if(this.getCotisationPayee()){
    			strCotis = "Payée";
    		} else {
    			strCotis = "Non payée";
    		}
    		return strCotis;
    	}
     
    	public Niveaux getNiveau() {return niveau.get();}
    	public void setNiveau(Niveaux niveau_) {this.niveau.set(niveau_);}
    	public ObjectProperty<Niveaux> niveauProperty() {return niveau;}
    }
    Pour le niveau, j'ai utilisé un ObjectProperty<Niveaux> mais je ne sais pas si j'ai bien fait.

    Voici la classe Personne :
    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
    public class Personne {
     
    	//ATTRIBUTS
    	private StringProperty nom;
    	private StringProperty prenom;
    	private StringProperty adresse;
    	private ObjectProperty<LocalDate> date_naissance;
    	private StringProperty telephone1;
    	private StringProperty telephone2;
    	private StringProperty email1;
    	private StringProperty email2;
    	private IntegerProperty anciennete;
    	private List<String> instruments;
     
    	//CONSTRUCTEURS
    	public Personne() {this(null, null, null, null, null, null, null, null, 0, new ArrayList<String>());}
    	public Personne(String nom_, String prenom_, String adresse_, LocalDate date_naissance_, String telephone1_, String telephone2_,
    			String email1_, String email2_, Integer anciennete_, List<String> instruments_) {
    		this.nom = new SimpleStringProperty(nom_);
    		this.prenom = new SimpleStringProperty(prenom_);
    		this.adresse = new SimpleStringProperty(adresse_);
    		this.date_naissance  = new SimpleObjectProperty<LocalDate>(date_naissance_);
    		this.telephone1 = new SimpleStringProperty(telephone1_);
    		this.telephone2 = new SimpleStringProperty(telephone2_);
    		this.email1 = new SimpleStringProperty(email1_);
    		this.email2 = new SimpleStringProperty(email2_);
    		this.anciennete = new SimpleIntegerProperty(anciennete_);
     
    		ObservableList<String> observableList = FXCollections.observableArrayList(instruments_);
    		this.instruments = new SimpleListProperty<String>(observableList);
    	}
     
    	//ACCESSEURS
    	public String getNom() {return nom.get();}
    	public void setNom(String nom) {this.nom.set(nom);}
    	public StringProperty nomProperty(){return nom;}
     
    	public String getPrenom() {return prenom.get();}
    	public void setPrenom(String prenom) {this.prenom.set(prenom);}
    	public StringProperty prenomProperty(){return prenom;}
     
    	public String getAdresse() {return adresse.get();}
    	public void setAdresse(String adresse) {this.adresse.set(adresse);}
    	public StringProperty adresseProperty(){return adresse;}
     
    	public LocalDate getDate_naissance() {return date_naissance.get();}
    	public void setDate_naissance(LocalDate date_naissance) {this.date_naissance.set(date_naissance);}
    	public ObjectProperty<LocalDate> date_naissanceProperty(){return date_naissance;}
     
    	public String getTelephone1() {return telephone1.get();}
    	public void setTelephone1(String telephone1) {this.telephone1.set(telephone1);}
    	public StringProperty telephone1Property(){return telephone1;}
     
    	public String getTelephone2() {return telephone2.get();}
    	public void setTelephone2(String telephone2) {this.telephone2.set(telephone2);}
    	public StringProperty telephone2Property(){return telephone2;}
     
    	public String getEmail1() {return email1.get();}
    	public void setEmail1(String email1) {this.email1.set(email1);}
    	public StringProperty email1Property(){return email1;}
     
    	public String getEmail2() {return email2.get();}
    	public void setEmail2(String email2) {this.email2.set(email2);}
    	public StringProperty  email2Property(){return email2;}
     
    	public Integer getAnciennete() {return anciennete.get();}
    	public void setAnciennete(Integer anciennete) {this.anciennete.set(anciennete);}
     
    	public List<String> getInstruments() {return instruments;}
    	public void setInstruments(List<String> instruments) {this.instruments = instruments;}
    	public String getInstrumentsToString(){
    		StringBuilder sb = new StringBuilder();
            for(int i = 0; i < this.getInstruments().size(); i++){
            	sb.append(this.getInstruments().get(i));
            	if(i < this.getInstruments().size() - 1){
            		sb.append(", ");
            	}
            }
            return sb.toString();
    	}
    	public void setInstrumentsFromString(String instrus) {
    		this.setInstruments(Arrays.asList(instrus.split(",")));
    	}
    }
    J'ai aussi un controller nommé EleveEditDialogCtrl :
    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    public class EleveEditDialogCtrl {
     
    	@FXML
    	private TextField nomField;
     
    	@FXML
    	private TextField prenomField;
     
    	@FXML
    	private TextField adresseField;
     
    	@FXML
    	private TextField date_naissanceField;
     
    	@FXML
    	private TextField telephone1Field;
     
    	@FXML
    	private TextField telephone2Field;
     
    	@FXML
    	private TextField email1Field;
     
    	@FXML
    	private TextField email2Field;
     
    	@FXML
    	private TextField instrumentsField;
     
    	@FXML
    	private TextField niveauLabel;
     
    	@FXML
    	private TextField niveauValue;
     
     
    	private Stage eleveDialogStage;
    	private Eleve eleve;
    	private boolean okClicked = false;
     
    	/**
         * Initializes the controller class. This method is automatically called
         * after the fxml file has been loaded.
         */
    	@FXML
    	private void initialize() {
     
    	}
     
     
        /**
         * Sets the stage of this eleveDialog.
         *
         * @param dialogStage
         */
    	public void setEleveDialogStage(Stage eleveDialogStage){
    		this.eleveDialogStage = eleveDialogStage;
    	}
     
     
        /**
         * Sets the Eleve to be edited in the dialog.
         *
         * @param person
         */
    	public void setEleve(Eleve eleve){
    		this.eleve = eleve;
     
    		nomField.setText(eleve.getNom());
    		prenomField.setText(eleve.getPrenom());
    		adresseField.setText(eleve.getAdresse());
    		date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    		telephone1Field.setText(eleve.getTelephone1());
    		telephone2Field.setText(eleve.getTelephone2());
    		email1Field.setText(eleve.getEmail1());
    		email2Field.setText(eleve.getEmail2());
    		instrumentsField.setText(eleve.getInstrumentsToString());
    		niveauLabel.setText(eleve.getNiveau().getStrNiveau());
    		niveauValue.setText(String.valueOf(eleve.getNiveau().getIntNiveau()));
    	}
     
        /**
         * Returns true if the user clicked OK, false otherwise.
         *
         * @return
         */
        public boolean isOkClicked() {
            return okClicked;
        }
     
        @FXML
        private void handleOK() {
        	if(isInputValid()){
        		eleve.setNom(nomField.getText());
        		eleve.setPrenom(prenomField.getText());
        		eleve.setAdresse(adresseField.getText());
        		eleve.setDate_naissance(DateUtil.parse(date_naissanceField.getText()));
        		eleve.setTelephone1(telephone1Field.getText());
        		eleve.setTelephone2(telephone2Field.getText());
        		eleve.setEmail1(email1Field.getText());
        		eleve.setEmail2(email2Field.getText());
        		eleve.setInstrumentsFromString(instrumentsField.getText());
        		eleve.setNiveau(
        				new Niveaux(Integer.parseInt(niveauValue.getText()),
        						niveauLabel.getText())
        				);
        		eleve.setCotisationPayee(false);
     
        		okClicked = true;
        		eleveDialogStage.close();
        	}
        }
     
        /**
         * Called when the user clicks cancel.
         */
        @FXML
        private void handleAnnuler(){
        	eleveDialogStage.close();
        }
     
        /**
         * Validates the user input in the text fields.
         *
         * @return true if the input is valid
         */
        private boolean isInputValid() {
        	String errorMessage = "";
     
        	if(nomField.getText() == null || nomField.getText().length() == 0){
        		errorMessage += "Le champs 'nom' n'est pas valide\n";
        	}
        	if(prenomField.getText() == null || prenomField.getText().length() == 0){
        		errorMessage += "Le champs 'prénom' n'est pas valide\n";
        	}
        	if(adresseField.getText() == null){
        		errorMessage += "Le champs 'adresse' n'est pas valide\n";
        	}
            if (date_naissanceField.getText() == null) {
                errorMessage += "Le champs 'date de naissance' n'est pas valide\n";
            } else {
                if (!DateUtil.validDate(date_naissanceField.getText())) {
                    errorMessage += "Le champs 'date de naissance' n'est pas valide, utilisez le format jj.mm.aaaa\n";
                }
            }
        	if(telephone1Field.getText() == null){
        		errorMessage += "Le champs 'telephone 1' n'est pas valide\n";
        	}
        	if(telephone2Field.getText() == null){
        		errorMessage += "Le champs 'telephone 2' n'est pas valide\n";
        	}
        	if(email1Field.getText() == null){
        		errorMessage += "Le champs 'email 1' n'est pas valide\n";
        	}
        	if(email2Field.getText() == null){
        		errorMessage += "Le champs 'email 2' n'est pas valide\n";
        	}
        	if(instrumentsField.getText() == null){
        		errorMessage += "Le champs 'instruments' n'est pas valide\n";
        	}
     
     
            if (errorMessage.length() == 0) {
                return true;
            } else {
                // Show the error message.
                Alert alert = new Alert(AlertType.ERROR);
                alert.initOwner(eleveDialogStage);
                alert.setTitle("Champs invalides");
                alert.setHeaderText("Merci de corriger les champs");
                alert.setContentText(errorMessage);
     
                alert.showAndWait();
     
                return false;
            }
        }
    }
    Dans ce controller, j'ai du mal à récupérer un objet Enum Niveaux et j'ai bien l'impression que c'est impossible.

    Me faudra-t-il diviser l'attribut niveau dans la classe Eleve en deux attributs, 1 pour la valeur du Slider et 1 pour le label du Slider ?


    et voici le fichier de l'interface graphique EleveEditDialog.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
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    <?xml version="1.0" encoding="UTF-8"?>
     
    <?import javafx.scene.control.Button?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.Slider?>
    <?import javafx.scene.control.TextField?>
    <?import javafx.scene.layout.AnchorPane?>
    <?import javafx.scene.layout.ColumnConstraints?>
    <?import javafx.scene.layout.GridPane?>
    <?import javafx.scene.layout.RowConstraints?>
     
    <AnchorPane prefHeight="400.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8.0.72" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fr.ems.adherents.view.EleveEditDialogCtrl">
       <children>
          <GridPane AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0">
            <columnConstraints>
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="150.0" minWidth="10.0" prefWidth="100.0" />
              <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            </columnConstraints>
            <rowConstraints>
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            </rowConstraints>
             <children>
                <Label text="Nom" />
                <Label text="Prénom" GridPane.rowIndex="1" />
                <Label text="Adresse" GridPane.rowIndex="2" />
                <Label text="Tel 1" GridPane.rowIndex="4" />
                <Label text="Tel 2" GridPane.rowIndex="5" />
                <Label text="Email 1" GridPane.rowIndex="6" />
                <Label text="Email 2" GridPane.rowIndex="7" />
                <Label text="Date de naissance" GridPane.rowIndex="3" />
                <Label text="Instrument" GridPane.rowIndex="8" />
                <TextField fx:id="nomField" GridPane.columnIndex="1" />
                <TextField fx:id="prenomField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
                <TextField fx:id="adresseField" GridPane.columnIndex="1" GridPane.rowIndex="2" />
                <TextField fx:id="date_naissanceField" GridPane.columnIndex="1" GridPane.rowIndex="3" />
                <TextField fx:id="telephone1Field" GridPane.columnIndex="1" GridPane.rowIndex="4" />
                <TextField fx:id="telephone2Field" GridPane.columnIndex="1" GridPane.rowIndex="5" />
                <TextField fx:id="email1Field" GridPane.columnIndex="1" GridPane.rowIndex="6" />
                <TextField fx:id="email2Field" GridPane.columnIndex="1" GridPane.rowIndex="7" />
                <TextField fx:id="instrumentsField" GridPane.columnIndex="1" GridPane.rowIndex="8" />
                <Label text="Niveau" GridPane.rowIndex="9" />
                <Slider blockIncrement="20.0" majorTickUnit="20.0" showTickLabels="true" showTickMarks="true" snapToTicks="true" GridPane.columnIndex="1" GridPane.rowIndex="9" />
             </children>
          </GridPane>
          <Button mnemonicParsing="false" onAction="#handleOK" text="Valider" AnchorPane.bottomAnchor="5.0" AnchorPane.rightAnchor="5.0" />
          <Button layoutX="360.0" layoutY="369.0" mnemonicParsing="false" onAction="#handleAnnuler" text="Annuler" />
       </children>
    </AnchorPane>

    Et donc, au final, je souhaite que l'on voie le slider avec les niveaux inscrits mais j'ai du mal à imaginer la meilleur manière de faire cela.

    Merci pour vos aides !

    OS : LinuxMint 20

  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
    Pour résumer (parce qu'il était possible de faire un code de test bien plus épuré que nous fournir toute ton application ) tu as deux soucis :
    1. Tu veux afficher les labels des niveaux dans le Slider ;
    2. Quand l'utilisateur change la valeur du Slider (ce qui produit un double qui va être castés en int par nos soins), tu veux récupérer une instance de Niveaux. Or, comme tu l'as vu, tu ne peux pas invoquer le constructeur de l'enum (ce qui est tout à fait normal).


    Pour le problème #2, une manière très simple de faire est d'invoquer la méthode values() de la classe Niveaux et d'utiliser l'indice approprié pour récupérer la bonne valeurs de l'enum. En effet cet méthode retourne un tableau de valeur qui est ordonné dans l'ordre dans lequel les valeurs sont déclarées dans le code de l'enum. Donc ici on aura un tableau qui contiendra { EVEIL, DEBUTANT, ELEMENTAIRE, INTERMEDIAIRE, AVANCE }. Donc, dans ton cas, EVEIL est à l'indice 0 (ce qui correspond à sa valeur intNiveau), DEBUTANT est à l'indice 1, etc.

    Donc c'est plutôt direct :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    int intNiveau= Integer.parseInt(niveauValue.getText());
    Niveau niveau = Niveaux.values()[intNiveau];
    Quand ces valeurs ne correspondent pas, une manière plus safe de faire est de créer une nouvelle méthode dans l'enum pour récupérer la bonne valeur. Par exemple :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static Niveaux getNiveau(final int intNiveau) {
        Optional<Niveaux> result = Arrays.stream(values())
                .filter(nv -> nv.intNiveau == intNiveau)
                .findFirst();
        if (!result.isPresent()) {
            throw new IllegalArgumentException(String.valueOf(intNiveau));
        }
        return result.get();
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    int intNiveau= Integer.parseInt(niveauValue.getText());
    Niveau niveau = Niveaux.getNiveau(intNiveau);
    Pour le problème #1, on va commencer par donner un fx:id au Slider et ensuite le déclarer dans le contrôleur :

    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    <Slider fx:id="niveauxSlider"

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    @FXML
    private Slider niveauxSlider;
    Et ensuite le code pour configurer correctement le Slider :

    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
    @FXML
    private void initialize() {
        niveauxSlider.setMin(Niveaux.EVEIL.getIntNiveau());
        niveauxSlider.setMax(Niveaux.AVANCE.getIntNiveau());
        niveauxSlider.setMajorTickUnit(1);
        niveauxSlider.setMinorTickCount(0);
        niveauxSlider.setBlockIncrement(1);
        niveauxSlider.setLabelFormatter(new StringConverter<Double>() {
            @Override
            public String toString(Double object) {
                int intNiveau = object.intValue();
                Niveaux niveau = Niveaux.getNiveau(intNiveau);
                return niveau.getStrNiveau();
            }
     
            @Override
            public Double fromString(String string) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });
    }
    Nom : Sans titre.jpg
Affichages : 778
Taille : 8,3 Ko

    PS : on est sensé mettre des accents sur les majuscules en Français : Accentuation des majuscules sur le site de l'Académie Française. Microsoft, Apple et pas mal d'éditeur majeurs suivent cette règle (même si les correcteurs orthographiques autorisent souvent les deux orthographes).
    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 informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut
    Bonjour et merci pour la leçon de Français dans notre monde de plus en plus américanisé (pourtant, il a bien d'autres pays et langues intéressants sur cette planète).... One point

    Pour ce qui est de la value que j'ai définie en int, je peux la modifier en double si cela est préférable. Je l'avais mise en int car je pensais que le slider produisait du int.

    Pour ce qui est de votre proposition de code, je vais m'appliquer à le respecter, je vous donnerai les résultats lorsque j'aurais finalisé ce slider ... ou pas !



    En tout cas, merci beaucoup pour vos explications précises et claires
    OS : LinuxMint 20

  4. #4
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut
    Bonsoir,

    Je rencontre un problème sur l'accesseur "setNiveau(Niveaux niveau) de la classe Eleve qui est appelé depuis le constructeur.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public void setNiveau(Niveaux niveau_) {this.niveau.set(niveau_);}
    J'ai déclaré le niveau comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    private ObjectProperty<Niveaux> niveau;
    voici le rapport d'erreur dans la console :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    Exception in Application constructor
    java.lang.reflect.InvocationTargetException
    ......
    Caused by: java.lang.NullPointerException
    	at fr.ems.adherents.model.Eleve.setNiveau(Eleve.java:52)
    Ce rapport me dit un NullPointerException alors que ni "this", ni "niveau_" ne sont nulls ...

    Pensez-vous qu'il me faille modifier le type de niveau dans la classe Eleve ?

    De plus, je n'ai pas bien compris pour les deux lignes suivantes que vous m'aviez indiquées :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    int intNiveau= Integer.parseInt(niveauValue.getText());
    Niveau niveau = Niveaux.getNiveau(intNiveau);
    Dois-je les saisir telles qu'elles dans la classe EleveEditDialogCtrl ?

    Perso j'ai modifié EleveEditDialogCtrl comme ceci en suivant vos conseils :
    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
      */
    	@FXML
    	private void initialize() {
    	    niveauxSlider.setMin(Niveaux.EVEIL.getIntNiveau());
    	    niveauxSlider.setMax(Niveaux.AVANCE.getIntNiveau());
    	    niveauxSlider.setMajorTickUnit(1);
    	    niveauxSlider.setMinorTickCount(0);
    	    niveauxSlider.setBlockIncrement(1);
    	    niveauxSlider.setLabelFormatter(new StringConverter<Double>() {
    	        @Override
    	        public String toString(Double object) {
    	            int intNiveau = object.intValue();
    	            Niveaux niveau = Niveaux.getNiveau(intNiveau);
    	            return niveau.getStrNiveau();
    	        }
     
    	        @Override
    	        public Double fromString(String string) {
    	            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    	        }
    	    });
    	}
     
    .......
     
        /**
         * Sets the Eleve to be edited in the dialog.
         *
         * @param person
         */
    	public void setEleve(Eleve eleve){
    		this.eleve = eleve;
     
    		nomField.setText(eleve.getNom());
    		prenomField.setText(eleve.getPrenom());
    		adresseField.setText(eleve.getAdresse());
    		date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    		telephone1Field.setText(eleve.getTelephone1());
    		telephone2Field.setText(eleve.getTelephone2());
    		email1Field.setText(eleve.getEmail1());
    		email2Field.setText(eleve.getEmail2());
    		instrumentsField.setText(eleve.getInstrumentsToString());
    		niveauLabel.setText(eleve.getNiveau().getStrNiveau());
    		niveauValue.setText(String.valueOf(eleve.getNiveau().getIntNiveau()));
    	}
     
    ........
     
        @FXML
        private void handleOK() {
        	if(isInputValid()){
        		eleve.setNom(nomField.getText());
        		eleve.setPrenom(prenomField.getText());
        		eleve.setAdresse(adresseField.getText());
        		eleve.setDate_naissance(DateUtil.parse(date_naissanceField.getText()));
        		eleve.setTelephone1(telephone1Field.getText());
        		eleve.setTelephone2(telephone2Field.getText());
        		eleve.setEmail1(email1Field.getText());
        		eleve.setEmail2(email2Field.getText());
        		eleve.setInstrumentsFromString(instrumentsField.getText());
    			int intNiveau= Integer.parseInt(niveauValue.getText());
        		eleve.setNiveau(Niveaux.getNiveau(intNiveau));
        		eleve.setCotisationPayee(false);
     
        		okClicked = true;
        		eleveDialogStage.close();
        	}
        }
    Merci,
    OS : LinuxMint 20

  5. #5
    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
    Pourquoi changer les int en double, c'est tres bien comme c'est actuellement.

    Pour ta NullPointerException, ben faudrait penser a initialiser la propriété quand même... par exemple :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    private ObjectProperty<Niveaux> niveau = new SimpleObjectProperty<>(this, "niveau", Niveaux.EVEIL);
    De plus, je n'ai pas bien compris pour les deux lignes suivantes que vous m'aviez indiquées :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    int intNiveau= Integer.parseInt(niveauValue.getText());
    Niveau niveau = Niveaux.getNiveau(intNiveau);
    Dois-je les saisir telles qu'elles dans la classe EleveEditDialogCtrl ?
    Ben a l'endroit ou tu tentais de faire :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    eleve.setNiveau(
        				new Niveaux(Integer.parseInt(niveauValue.getText()),
        						niveauLabel.getText())
        				);
    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 informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut
    Bonjour et merci !

    OK, c'est pas très évident de trouver l'erreur car en mode débug je vois que rien n'est null ...

    Très intéressant ce constructeur de SimpleObjectProperty :
    public SimpleObjectProperty(java.lang.Object bean,
    java.lang.String name,
    T initialValue)

    The constructor of ObjectProperty

    Parameters:
    bean - the bean of this ObjectProperty
    name - the name of this ObjectProperty
    initialValue - the initial value of the wrapped value
    Par contre, dans le même style que précédemment, je suis bloqué à la ligne 13 de la méthode suivante pour un nullPointerException alors que rien n'est null :
    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
    public void setEleve(Eleve eleve){
    	this.eleve = eleve;
     
    	nomField.setText(eleve.getNom());
    	prenomField.setText(eleve.getPrenom());
    	adresseField.setText(eleve.getAdresse());
    	date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    	telephone1Field.setText(eleve.getTelephone1());
    	telephone2Field.setText(eleve.getTelephone2());
    	email1Field.setText(eleve.getEmail1());
    	email2Field.setText(eleve.getEmail2());
    	instrumentsField.setText(eleve.getInstrumentsToString());
    	niveauLabel.setText(eleve.getNiveau().getStrNiveau());
    	niveauValue.setText(String.valueOf(eleve.getNiveau().getIntNiveau()));
    }
    et voici la trace dans la console :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    ...............
    Caused by: java.lang.NullPointerException
    	at fr.ems.adherents.view.EleveEditDialogCtrl.setEleve(EleveEditDialogCtrl.java:110)
    et ici la classe Eleve :
    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    package fr.ems.adherents.view;
     
    import fr.ems.adherents.model.Eleve;
    import fr.ems.adherents.model.Niveaux;
    import fr.ems.adherents.util.DateUtil;
    import javafx.fxml.FXML;
    import javafx.scene.control.Alert;
    import javafx.scene.control.Alert.AlertType;
    import javafx.scene.control.Slider;
    import javafx.scene.control.TextField;
    import javafx.stage.Stage;
    import javafx.util.StringConverter;
     
    public class EleveEditDialogCtrl {
     
    	@FXML
    	private TextField nomField;
     
    	@FXML
    	private TextField prenomField;
     
    	@FXML
    	private TextField adresseField;
     
    	@FXML
    	private TextField date_naissanceField;
     
    	@FXML
    	private TextField telephone1Field;
     
    	@FXML
    	private TextField telephone2Field;
     
    	@FXML
    	private TextField email1Field;
     
    	@FXML
    	private TextField email2Field;
     
    	@FXML
    	private TextField instrumentsField;
     
    	@FXML
    	private TextField niveauLabel;
     
    	@FXML
    	private TextField niveauValue;
     
    	@FXML
    	private Slider niveauxSlider;
     
    	private Stage eleveDialogStage;
    	private Eleve eleve;
    	private boolean okClicked = false;
     
    	/**
         * Initializes the controller class. This method is automatically called
         * after the fxml file has been loaded.
         */
    	@FXML
    	private void initialize() {
    	    niveauxSlider.setMin(Niveaux.EVEIL.getIntNiveau());
    	    niveauxSlider.setMax(Niveaux.AVANCE.getIntNiveau());
    	    niveauxSlider.setMajorTickUnit(1);
    	    niveauxSlider.setMinorTickCount(0);
    	    niveauxSlider.setBlockIncrement(1);
    	    niveauxSlider.setLabelFormatter(new StringConverter<Double>() {
    	        @Override
    	        public String toString(Double object) {
    	            int intNiveau = object.intValue();
    	            Niveaux niveau = Niveaux.getNiveau(intNiveau);
    	            return niveau.getStrNiveau();
    	        }
     
    	        @Override
    	        public Double fromString(String string) {
    	            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    	        }
    	    });
    	}
     
     
        /**
         * Sets the stage of this eleveDialog.
         *
         * @param dialogStage
         */
    	public void setEleveDialogStage(Stage eleveDialogStage){
    		this.eleveDialogStage = eleveDialogStage;
    	}
     
     
        /**
         * Sets the Eleve to be edited in the dialog.
         *
         * @param person
         */
    public void setEleve(Eleve eleve){
    	this.eleve = eleve;
     
    	nomField.setText(eleve.getNom());
    	prenomField.setText(eleve.getPrenom());
    	adresseField.setText(eleve.getAdresse());
    	date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    	telephone1Field.setText(eleve.getTelephone1());
    	telephone2Field.setText(eleve.getTelephone2());
    	email1Field.setText(eleve.getEmail1());
    	email2Field.setText(eleve.getEmail2());
    	instrumentsField.setText(eleve.getInstrumentsToString());
    	niveauLabel.setText(eleve.getNiveau().getStrNiveau());
    	niveauValue.setText(String.valueOf(eleve.getNiveau().getIntNiveau()));
    }
     
        /**
         * Returns true if the user clicked OK, false otherwise.
         *
         * @return
         */
        public boolean isOkClicked() {
            return okClicked;
        }
     
    	@FXML
    	private void handleOK() {
    		if(isInputValid()){
    			eleve.setNom(nomField.getText());
    			eleve.setPrenom(prenomField.getText());
    			eleve.setAdresse(adresseField.getText());
    			eleve.setDate_naissance(DateUtil.parse(date_naissanceField.getText()));
    			eleve.setTelephone1(telephone1Field.getText());
    			eleve.setTelephone2(telephone2Field.getText());
    			eleve.setEmail1(email1Field.getText());
    			eleve.setEmail2(email2Field.getText());
    			eleve.setInstrumentsFromString(instrumentsField.getText());
    			int intNiveau= Integer.parseInt(niveauValue.getText());
    			eleve.setNiveau(Niveaux.getNiveau(intNiveau));
    			eleve.setCotisationPayee(false);
     
    			okClicked = true;
    			eleveDialogStage.close();
    		}
    	}
     
        /**
         * Called when the user clicks cancel.
         */
        @FXML
        private void handleAnnuler(){
        	eleveDialogStage.close();
        }
     
        /**
         * Validates the user input in the text fields.
         *
         * @return true if the input is valid
         */
        private boolean isInputValid() {
        	String errorMessage = "";
     
        	if(nomField.getText() == null || nomField.getText().length() == 0){
        		errorMessage += "Le champs 'nom' n'est pas valide\n";
        	}
        	if(prenomField.getText() == null || prenomField.getText().length() == 0){
        		errorMessage += "Le champs 'prénom' n'est pas valide\n";
        	}
        	if(adresseField.getText() == null){
        		errorMessage += "Le champs 'adresse' n'est pas valide\n";
        	}
            if (date_naissanceField.getText() == null) {
                errorMessage += "Le champs 'date de naissance' n'est pas valide\n";
            } else {
                if (!DateUtil.validDate(date_naissanceField.getText())) {
                    errorMessage += "Le champs 'date de naissance' n'est pas valide, utilisez le format jj.mm.aaaa\n";
                }
            }
        	if(telephone1Field.getText() == null){
        		errorMessage += "Le champs 'telephone 1' n'est pas valide\n";
        	}
        	if(telephone2Field.getText() == null){
        		errorMessage += "Le champs 'telephone 2' n'est pas valide\n";
        	}
        	if(email1Field.getText() == null){
        		errorMessage += "Le champs 'email 1' n'est pas valide\n";
        	}
        	if(email2Field.getText() == null){
        		errorMessage += "Le champs 'email 2' n'est pas valide\n";
        	}
        	if(instrumentsField.getText() == null){
        		errorMessage += "Le champs 'instruments' n'est pas valide\n";
        	}
     
     
            if (errorMessage.length() == 0) {
                return true;
            } else {
                // Show the error message.
                Alert alert = new Alert(AlertType.ERROR);
                alert.initOwner(eleveDialogStage);
                alert.setTitle("Champs invalides");
                alert.setHeaderText("Merci de corriger les champs");
                alert.setContentText(errorMessage);
     
                alert.showAndWait();
     
                return false;
            }
        }
    }
    Je me demande si j'ai bien fait de mettre le niveauValue en TextField ? Cela me gène (je débute en javaFX) car j'ai l'habitude de coder en java pur.

    OS : LinuxMint 20

  7. #7
    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
    Ça ne sert pas a grand chose de mettre le code de la classe Eleve si l'erreur te dis qu'elle se trouve dans la classe EleveEditDialogCtrl.

    C'est bien beau d’être sur et certain que c'est pas null mais tu as été quand même vérifier avec le débogueur que c'est bien le cas ?
    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

  8. #8
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut
    Bonjour,

    Oui, j'ai bien regardé en mode debug dans Eclipse.
    L'objet Eleve n'est pas null, son attribut "niveau" n'est pas null non plus l'accesseur renvoie donc l'objet Niveaux. Enfin, la méthode getStrNiveau() renvoie bien la chaîne de caractère convenue comme vous pouvez le voir dans la copie d'écran :
    Nom : erreur_javaFX.png
Affichages : 847
Taille : 170,5 Ko

    Par contre niveauLabel est null donc il me faut voir dans le controlleur comment il est initialisé !
    Dans le controlleur, c'est justement la méthode qui plante qui est censé initialiser cet attribut ...

    Je joins aussi le code du controlleur :
    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
     
    public class EleveEditDialogCtrl {
     
    	@FXML
    	private TextField nomField;
     
    	@FXML
    	private TextField prenomField;
     
    	@FXML
    	private TextField adresseField;
     
    	@FXML
    	private TextField date_naissanceField;
     
    	@FXML
    	private TextField telephone1Field;
     
    	@FXML
    	private TextField telephone2Field;
     
    	@FXML
    	private TextField email1Field;
     
    	@FXML
    	private TextField email2Field;
     
    	@FXML
    	private TextField instrumentsField;
     
    	@FXML
    	private TextField niveauLabel;
     
    	@FXML
    	private TextField niveauValue;
     
    	@FXML
    	private Slider niveauxSlider;
     
    	private Stage eleveDialogStage;
    	private Eleve eleve;
    	private boolean okClicked = false;
     
    	/**
         * Initializes the controller class. This method is automatically called
         * after the fxml file has been loaded.
         */
    	@FXML
    	private void initialize() {
    	    niveauxSlider.setMin(Niveaux.EVEIL.getIntNiveau());
    	    niveauxSlider.setMax(Niveaux.AVANCE.getIntNiveau());
    	    niveauxSlider.setMajorTickUnit(1);
    	    niveauxSlider.setMinorTickCount(0);
    	    niveauxSlider.setBlockIncrement(1);
    	    niveauxSlider.setLabelFormatter(new StringConverter<Double>() {
    	        @Override
    	        public String toString(Double object) {
    	            int intNiveau = object.intValue();
    	            Niveaux niveau = Niveaux.getNiveau(intNiveau);
    	            return niveau.getStrNiveau();
    	        }
     
    	        @Override
    	        public Double fromString(String string) {
    	            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    	        }
    	    });
    	}
     
     
        /**
         * Sets the stage of this eleveDialog.
         *
         * @param dialogStage
         */
    	public void setEleveDialogStage(Stage eleveDialogStage){
    		this.eleveDialogStage = eleveDialogStage;
    	}
     
     
        /**
         * Sets the Eleve to be edited in the dialog.
         *
         * @param person
         */
    public void setEleve(Eleve eleve){
    	this.eleve = eleve;
     
    	nomField.setText(eleve.getNom());
    	prenomField.setText(eleve.getPrenom());
    	adresseField.setText(eleve.getAdresse());
    	date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    	telephone1Field.setText(eleve.getTelephone1());
    	telephone2Field.setText(eleve.getTelephone2());
    	email1Field.setText(eleve.getEmail1());
    	email2Field.setText(eleve.getEmail2());
    	instrumentsField.setText(eleve.getInstrumentsToString());
    	niveauLabel.setText(eleve.getNiveau().getStrNiveau());
    	niveauValue.setText(String.valueOf(eleve.getNiveau().getIntNiveau()));
    }
     
        /**
         * Returns true if the user clicked OK, false otherwise.
         *
         * @return
         */
        public boolean isOkClicked() {
            return okClicked;
        }
     
    	@FXML
    	private void handleOK() {
    		if(isInputValid()){
    			eleve.setNom(nomField.getText());
    			eleve.setPrenom(prenomField.getText());
    			eleve.setAdresse(adresseField.getText());
    			eleve.setDate_naissance(DateUtil.parse(date_naissanceField.getText()));
    			eleve.setTelephone1(telephone1Field.getText());
    			eleve.setTelephone2(telephone2Field.getText());
    			eleve.setEmail1(email1Field.getText());
    			eleve.setEmail2(email2Field.getText());
    			eleve.setInstrumentsFromString(instrumentsField.getText());
    			int intNiveau= Integer.parseInt(niveauValue.getText());
    			eleve.setNiveau(Niveaux.getNiveau(intNiveau));
    			eleve.setCotisationPayee(false);
     
    			okClicked = true;
    			eleveDialogStage.close();
    		}
    	}
     
        /**
         * Called when the user clicks cancel.
         */
        @FXML
        private void handleAnnuler(){
        	eleveDialogStage.close();
        }
     
        /**
         * Validates the user input in the text fields.
         *
         * @return true if the input is valid
         */
        private boolean isInputValid() {
        	String errorMessage = "";
     
        	if(nomField.getText() == null || nomField.getText().length() == 0){
        		errorMessage += "Le champs 'nom' n'est pas valide\n";
        	}
        	if(prenomField.getText() == null || prenomField.getText().length() == 0){
        		errorMessage += "Le champs 'prénom' n'est pas valide\n";
        	}
        	if(adresseField.getText() == null){
        		errorMessage += "Le champs 'adresse' n'est pas valide\n";
        	}
            if (date_naissanceField.getText() == null) {
                errorMessage += "Le champs 'date de naissance' n'est pas valide\n";
            } else {
                if (!DateUtil.validDate(date_naissanceField.getText())) {
                    errorMessage += "Le champs 'date de naissance' n'est pas valide, utilisez le format jj.mm.aaaa\n";
                }
            }
        	if(telephone1Field.getText() == null){
        		errorMessage += "Le champs 'telephone 1' n'est pas valide\n";
        	}
        	if(telephone2Field.getText() == null){
        		errorMessage += "Le champs 'telephone 2' n'est pas valide\n";
        	}
        	if(email1Field.getText() == null){
        		errorMessage += "Le champs 'email 1' n'est pas valide\n";
        	}
        	if(email2Field.getText() == null){
        		errorMessage += "Le champs 'email 2' n'est pas valide\n";
        	}
        	if(instrumentsField.getText() == null){
        		errorMessage += "Le champs 'instruments' n'est pas valide\n";
        	}
     
     
            if (errorMessage.length() == 0) {
                return true;
            } else {
                // Show the error message.
                Alert alert = new Alert(AlertType.ERROR);
                alert.initOwner(eleveDialogStage);
                alert.setTitle("Champs invalides");
                alert.setHeaderText("Merci de corriger les champs");
                alert.setContentText(errorMessage);
     
                alert.showAndWait();
     
                return false;
            }
        }
    }
    Merci pour votre aide !
    OS : LinuxMint 20

  9. #9
    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
    Dans ce cas il ne reste que niveauLabel ce qui veut a nouveau dire :
    1. Soit un fx:id manquant ou mal écrit dans le FXML ou en tout cas pas identique au nom de la variable dans le contrôleur.
    2. Soit un contrôleur qui a été chargé en double a cause d'une mauvaise initialisation du FXML (car le programmeur ne sait pas trop de qu'il fait ).
    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

  10. #10
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2008
    Messages
    757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Février 2008
    Messages : 757
    Points : 572
    Points
    572
    Par défaut
    Bonjour,

    J'ai réussi à faire mon Slider avec des textes pour les Tick Labels.

    Tout d'abord, les attributs niveauValue et niveauLabel ont disparus. La méthode setLabelFormatter s'occupe des paramétrer les valeurs des Tick Labels.

    Voici le code du controller :
    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    package fr.ems.adherents.view;
     
    import fr.ems.adherents.model.Eleve;
    import fr.ems.adherents.model.Niveaux;
    import fr.ems.adherents.util.DateUtil;
    import javafx.fxml.FXML;
    import javafx.scene.control.Alert;
    import javafx.scene.control.Alert.AlertType;
    import javafx.scene.control.Label;
    import javafx.scene.control.Slider;
    import javafx.scene.control.TextField;
    import javafx.stage.Stage;
    import javafx.util.StringConverter;
     
    public class EleveEditDialogCtrl {
     
    	@FXML
    	private TextField nomField;
     
    	@FXML
    	private TextField prenomField;
     
    	@FXML
    	private TextField adresseField;
     
    	@FXML
    	private TextField date_naissanceField;
     
    	@FXML
    	private TextField telephone1Field;
     
    	@FXML
    	private TextField telephone2Field;
     
    	@FXML
    	private TextField email1Field;
     
    	@FXML
    	private TextField email2Field;
     
    	@FXML
    	private TextField instrumentsField;
     
    	@FXML
    	private Label niveauLabel;
     
    	@FXML
    	private TextField niveauValue;
     
    	@FXML
    	private Slider niveauxSlider;
     
    	private Stage eleveDialogStage;
    	private Eleve eleve;
    	private boolean okClicked = false;
     
    	/**
         * Initializes the controller class. This method is automatically called
         * after the fxml file has been loaded.
         */
    	@FXML
    	private void initialize() {
    	    niveauxSlider.setMin(Niveaux.EVEIL.getIntNiveau());
    	    niveauxSlider.setMax(Niveaux.AVANCE.getIntNiveau());
    	    niveauxSlider.setValue(Niveaux.EVEIL.getIntNiveau());
    	    niveauxSlider.setShowTickLabels(true);
    	    niveauxSlider.setShowTickMarks(true);
    	    niveauxSlider.setSnapToTicks(true);
    	    niveauxSlider.setMajorTickUnit(1);
    	    niveauxSlider.setMinorTickCount(0);
    	    niveauxSlider.setBlockIncrement(1);
    	    niveauxSlider.setLabelFormatter(new StringConverter<Double>() {
    	        @Override
    	        public String toString(Double object) {
    	            int intNiveau = object.intValue();
    	            Niveaux niveau = Niveaux.getNiveau(intNiveau);
    	            return niveau.getStrNiveau();
    	        }
     
    	        @Override
    	        public Double fromString(String string) {
    	            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    	        }
    	    });
    	}
     
     
        /**
         * Sets the stage of this eleveDialog.
         *
         * @param dialogStage
         */
    	public void setEleveDialogStage(Stage eleveDialogStage){
    		this.eleveDialogStage = eleveDialogStage;
    	}
     
     
        /**
         * Sets the Eleve to be edited in the dialog.
         *
         * @param person
         */
    public void setEleve(Eleve eleve){
    	this.eleve = eleve;
     
    	nomField.setText(eleve.getNom());
    	prenomField.setText(eleve.getPrenom());
    	adresseField.setText(eleve.getAdresse());
    	date_naissanceField.setText(DateUtil.format(eleve.getDate_naissance()));
    	telephone1Field.setText(eleve.getTelephone1());
    	telephone2Field.setText(eleve.getTelephone2());
    	email1Field.setText(eleve.getEmail1());
    	email2Field.setText(eleve.getEmail2());
    	instrumentsField.setText(eleve.getInstrumentsToString());
    	niveauxSlider.setValue((double) eleve.getNiveau().getIntNiveau());
    }
     
        /**
         * Returns true if the user clicked OK, false otherwise.
         *
         * @return
         */
        public boolean isOkClicked() {
            return okClicked;
        }
     
    	@FXML
    	private void handleOK() {
    		if(isInputValid()){
    			eleve.setNom(nomField.getText());
    			eleve.setPrenom(prenomField.getText());
    			eleve.setAdresse(adresseField.getText());
    			eleve.setDate_naissance(DateUtil.parse(date_naissanceField.getText()));
    			eleve.setTelephone1(telephone1Field.getText());
    			eleve.setTelephone2(telephone2Field.getText());
    			eleve.setEmail1(email1Field.getText());
    			eleve.setEmail2(email2Field.getText());
    			eleve.setInstrumentsFromString(instrumentsField.getText());
    			int intNiveau= Integer.parseInt(niveauValue.getText());
    			eleve.setNiveau(Niveaux.getNiveau(intNiveau));
    			eleve.setCotisationPayee(false);
     
    			okClicked = true;
    			eleveDialogStage.close();
    		}
    	}
     
        /**
         * Called when the user clicks cancel.
         */
        @FXML
        private void handleAnnuler(){
        	eleveDialogStage.close();
        }
     
        /**
         * Validates the user input in the text fields.
         *
         * @return true if the input is valid
         */
        private boolean isInputValid() {
        	String errorMessage = "";
     
        	if(nomField.getText() == null || nomField.getText().length() == 0){
        		errorMessage += "Le champs 'nom' n'est pas valide\n";
        	}
        	if(prenomField.getText() == null || prenomField.getText().length() == 0){
        		errorMessage += "Le champs 'prénom' n'est pas valide\n";
        	}
        	if(adresseField.getText() == null){
        		errorMessage += "Le champs 'adresse' n'est pas valide\n";
        	}
            if (date_naissanceField.getText() == null) {
                errorMessage += "Le champs 'date de naissance' n'est pas valide\n";
            } else {
                if (!DateUtil.validDate(date_naissanceField.getText())) {
                    errorMessage += "Le champs 'date de naissance' n'est pas valide, utilisez le format jj.mm.aaaa\n";
                }
            }
        	if(telephone1Field.getText() == null){
        		errorMessage += "Le champs 'telephone 1' n'est pas valide\n";
        	}
        	if(telephone2Field.getText() == null){
        		errorMessage += "Le champs 'telephone 2' n'est pas valide\n";
        	}
        	if(email1Field.getText() == null){
        		errorMessage += "Le champs 'email 1' n'est pas valide\n";
        	}
        	if(email2Field.getText() == null){
        		errorMessage += "Le champs 'email 2' n'est pas valide\n";
        	}
        	if(instrumentsField.getText() == null){
        		errorMessage += "Le champs 'instruments' n'est pas valide\n";
        	}
     
     
            if (errorMessage.length() == 0) {
                return true;
            } else {
                // Show the error message.
                Alert alert = new Alert(AlertType.ERROR);
                alert.initOwner(eleveDialogStage);
                alert.setTitle("Champs invalides");
                alert.setHeaderText("Merci de corriger les champs");
                alert.setContentText(errorMessage);
     
                alert.showAndWait();
     
                return false;
            }
        }
    }
    Merci pour votre aide
    OS : LinuxMint 20

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

Discussions similaires

  1. Peut-on créer un array avec des index de type String ?
    Par totoAussi dans le forum Collection et Stream
    Réponses: 5
    Dernier message: 13/03/2012, 14h06
  2. Réponses: 2
    Dernier message: 26/04/2006, 08h53
  3. Créer du xml avec des données Oracle
    Par Baumont dans le forum Oracle
    Réponses: 3
    Dernier message: 23/11/2005, 15h35
  4. Créer une vue avec des requêtes UNION ?
    Par webtheque dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 04/04/2005, 12h37
  5. créer un noeuds avec des paramétres
    Par Toxine77 dans le forum XMLRAD
    Réponses: 5
    Dernier message: 21/01/2003, 16h11

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