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

AWT/Swing Java Discussion :

Problème PropertyChangeListener avec JTable


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Septembre 2017
    Messages : 176
    Par défaut Problème PropertyChangeListener avec JTable
    Bonjour,
    j'essaie de rendre dynamique un update dans une JTable, c'est à dire, que lorsque je fait un update sur un client, que la mise à jour soi directement visible dans ma JTable, sans devoir fermer et ré-ouvrir la fenêtre.

    Nom : JTable.PNG
Affichages : 588
Taille : 54,9 Ko

    Concrètement, j'ai une classe qui étend JDialog et impléments PropertyChangeListener (TabUpdateClient), qui est ma fenêtre avec ma JTable, lorsque je clic sur un bouton mofifier, une nouvelle fenêtre JDialog s'ouvre (FormUpdateClient), c'est un formulaire permettant de faire des modifications sur un client. Lorsque je clic sur valider, je reviens vers mon controler, dans lequel j'ai plusieurs méthode d'affichage et mon CRUD. Controler dans lequel j'instancie mon PropertyChangeSupport, je crée le listener lorsque je rends visible ma JTable (showTabUpdateClient) et je notifie un changement dans updateClient.

    TabUpdateClient
    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
    package be.iepscfjemelle.nicolay.projet_sgbd.vues;
     
    import be.iepscfjemelle.projet_sgbd.controler.Controler;
    import be.iepscfjemelle.projet_sgbd.model.Client;
    import com.sun.javafx.webkit.theme.Renderer;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import static java.awt.Component.CENTER_ALIGNMENT;
    import java.awt.Container;
    import java.awt.Font;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import java.util.Collection;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
     
    /**
     * Class qui va me permettre de de choisir un client dans une table pour faire
     * une modification
     *
     */
    public class TabUpdateClient extends JDialog implements PropertyChangeListener{
     
        /**
         * Attributs
         */
        private final Controler contr;
        private final ArrayList list;
     
        /**
         * Attributs graphique
         */
        private JPanel mainPanel, panelhaut;
        private JLabel label;
        private JTable tableau;
     
        /**
         * Constructeur
         *
         * @param list
         * @param contr
         */
        public TabUpdateClient(ArrayList list, Controler contr) {
            this.contr = contr;
            this.list = list;
            initComponent();
        }
     
        private void initComponent() {
            //Config de la fenêtre
            setTitle("Modification des clients");
            setSize(1200, 700);
            setResizable(true);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
            Container contenu = getContentPane();
     
            //Config du label et de la table.
            //création de mon panel principal
            mainPanel = new JPanel();
            mainPanel.setLayout(new BorderLayout());
            contenu.add(mainPanel);
     
            //Création du panel du haut
            panelhaut = new JPanel();
            mainPanel.add(panelhaut, BorderLayout.NORTH);
     
            //Creation et config du tableau
            tableau = new JTable(new TabModelUpdateClients(this.list));
            tableau.getTableHeader().setBackground(Color.blue);//fond entête colonne
            tableau.getTableHeader().setForeground(Color.WHITE);//Couleur police entêtecolonne
            JScrollPane tabContainer = new JScrollPane(tableau);
            tableau.setAutoCreateRowSorter(true);//Permet le tri en cliquant sur le entête de colonne   
            mainPanel.add(tabContainer, BorderLayout.CENTER);
     
            //ajout du label au panel du haut
            label = new JLabel("Nombres de clients: " + tableau.getRowCount(), (int) CENTER_ALIGNMENT);
            Font font = new Font("Arial", Font.BOLD, 20);
            label.setFont(font);
            panelhaut.add(label);
     
            /**
             * TableCellRenderer pour les String, qui permet de donné un rendu aux
             * cellule d'un tableau, via une classe anonyme. Si Paire, fond blanc,
             * impaire fond gris légé.
             */
            tableau.setDefaultRenderer(Object.class,
                    new TableCellRenderer() {
                private final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
     
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    Component cel = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    if (row % 2 == 0) {
                        cel.setBackground(Color.WHITE);
                    } else {
                        cel.setBackground(Color.LIGHT_GRAY);
                    }
                    return cel;
                }
            }
            );
     
            /**
             * Appel de ma class TableButton
             */
            TableButton button = new TableButton() {
                private static final long serialVersionUID = 1L;
     
                protected String getButtonText(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                    return String.valueOf(value);
                }
                //pas utilisé ici
                protected void actionPerformed(JTable table, Object value, int row,
                        int column) {
                    //System.out.println("Action sur ligne " + row + " et colonne " + column);   
                }
            };
            // boutton sur la colonne 8
            button.install(tableau, 8);
     
            /**
             * fenetre de confirmation quand clic croix
             */
            addWindowListener(
                    new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e
                ) {
                    int confirmed = JOptionPane.showConfirmDialog(null, "Voulez-vous quitter la fenêtre?", "Quitter modification client", JOptionPane.YES_NO_OPTION);
                    if (confirmed == JOptionPane.YES_OPTION) {
                        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    } else {
                        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    }
                }
            }
            );
     
            /**
             * méthode qui va permettre de recréer un objet à partir d'un clic de
             * souris sur un des boutons modifier
             *
             * @param event
             */
            tableau.addMouseListener(new java.awt.event.MouseAdapter() {//class anonyme         
                @Override
                public void mouseClicked(java.awt.event.MouseEvent event) {
                    int row = tableau.rowAtPoint(event.getPoint());//renvoie le numéro de la ligne
                    //on récupère les info dans la ligne clickée et dans chaque colonne pour recréer un objet à partir d'un clic dans une colonne
                    Client clientSelected = new Client();
                    clientSelected.setIdClient((int) tableau.getModel().getValueAt(row, 0));
                    clientSelected.setNumeroNational((String) tableau.getModel().getValueAt(row, 1));
                    clientSelected.setNomClient((String) tableau.getModel().getValueAt(row, 2));
                    clientSelected.setPrenomClient((String) tableau.getModel().getValueAt(row, 3));
                    clientSelected.setTelephoneClient((String) tableau.getModel().getValueAt(row, 4));
                    clientSelected.setMailClient((String) tableau.getModel().getValueAt(row, 5));
                    clientSelected.setDateNaissanceClient((String) tableau.getModel().getValueAt(row, 6));
                    clientSelected.setAdresseClient((String) tableau.getModel().getValueAt(row, 7));
                    System.out.println(clientSelected.adresseClient);
                    //clic sur une ligne client affiche une deuxième fenêtre, mon formulaire d'update client
                    if (tableau.getSelectedColumn() == 8) {
                        contr.showFormUpdateClient(clientSelected);
                    }
                }
            });
        }
     
        /**
         * @param evt 
         */
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("Listener Client")) {
               Client client = (Client) evt.getNewValue();//CHARGER Client ou liste de Client???
            }
     
        }
     
    }
    FormUpdateClient
    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
    213
    214
    215
    216
    217
    218
    219
    220
    package be.iepscfjemelle.projet_sgbd.vues;
     
    import be.iepscfjemelle.projet_sgbd.controler.Controler;
    import java.awt.Container;
    //import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
     
    /**
     *
     */
    public class FormUpdateClient extends JDialog implements ActionListener {
     
        /**
         * Attributs graphiques
         */
        private JTextField fieldId, fieldNumNat, fieldNom, fieldPrenom, fieldTel, fieldMail, fieldDateNaissance, fieldAdresse;
        private JButton accueil, valider;
     
        /**
         * Attributs
         */
        private final Controler contr;
        private int id;
        private String numNat, nom, prenom, tel, mail, dateNaiss, adresse;
     
        public FormUpdateClient(int idClient, String numeroNational, String nomClient, String prenomClient,
                String telephoneClient, String mailClient, String dateNaissanceClient, String adresseClient, Controler contr) {
            this.contr = contr;
            this.id = idClient;
            this.numNat = numeroNational;
            this.nom = nomClient;
            this.prenom = prenomClient;
            this.tel = telephoneClient;
            this.mail = mailClient;
            this.dateNaiss = dateNaissanceClient;
            this.adresse = adresseClient;
            initComponents();
            System.out.println(nom);
        }
     
        private void initComponents() {
            //Config de la fenêtre
            setTitle("modification du client");
            setSize(500, 800);
            setModal(true);
            setResizable(false);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
            Container contenu1 = getContentPane();
     
            //Config du grid layout (Nlignes, NCol, H gap, V gap)
            contenu1.setLayout(new GridLayout(10, 1, 20, 10));
            //contenu2.setLayout(new GridLayout(1, 2, 20, 10));
     
            //form id
            JPanel panel0 = new JPanel();
            panel0.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelId = new JLabel("Id client:");
            labelId.setPreferredSize(new Dimension(150, 30));
            panel0.add(labelId);
            fieldId = new JTextField();
            fieldId.setPreferredSize(new Dimension(250, 30));
            fieldId.setText(String.valueOf(id));
            fieldId.setEnabled(false);
            panel0.add(fieldId);
            contenu1.add(panel0);
     
            //form fieldNumNat
            JPanel panel1 = new JPanel();
            panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelNumNat = new JLabel("Numéro national:");
            labelNumNat.setPreferredSize(new Dimension(150, 30));
            panel1.add(labelNumNat);
            fieldNumNat = new JTextField();
            fieldNumNat.setPreferredSize(new Dimension(250, 30));
            fieldNumNat.setText(numNat);
            fieldNumNat.setEnabled(false);
            panel1.add(fieldNumNat);
            contenu1.add(panel1);
     
            //form fieldNom
            JPanel panel2 = new JPanel();
            panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelNom = new JLabel("Nom du client:");
            labelNom.setPreferredSize(new Dimension(150, 30));
            panel2.add(labelNom);
            fieldNom = new JTextField();
            fieldNom.setPreferredSize(new Dimension(250, 30));
            fieldNom.setText(nom);
            panel2.add(fieldNom);
            contenu1.add(panel2);
     
            //form fieldPrenom
            JPanel panel3 = new JPanel();
            panel3.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelPrenom = new JLabel("Prenom du client:");
            labelPrenom.setPreferredSize(new Dimension(150, 30));
            panel3.add(labelPrenom);
            fieldPrenom = new JTextField();
            fieldPrenom.setPreferredSize(new Dimension(250, 30));
            fieldPrenom.setText(prenom);
            panel3.add(fieldPrenom);
            contenu1.add(panel3);
     
            //form fieldTel
            JPanel panel4 = new JPanel();
            panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelTel = new JLabel("Telephone client:");
            labelTel.setPreferredSize(new Dimension(150, 30));
            panel4.add(labelTel);
            fieldTel = new JTextField();
            fieldTel.setPreferredSize(new Dimension(250, 30));
            fieldTel.setText(tel);
            panel4.add(fieldTel);
            contenu1.add(panel4);
     
            //form fieldMail
            JPanel panel5 = new JPanel();
            panel5.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelMail = new JLabel("Email client:");
            labelMail.setPreferredSize(new Dimension(150, 30));
            panel5.add(labelMail);
            fieldMail = new JTextField();
            fieldMail.setPreferredSize(new Dimension(250, 30));
            fieldMail.setText(mail);
            panel5.add(fieldMail);
            contenu1.add(panel5);
     
            //form fieldDateNaissance
            JPanel panel6 = new JPanel();
            panel6.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelDateNaissance = new JLabel("Date naissance:");
            labelDateNaissance.setPreferredSize(new Dimension(150, 30));
            panel6.add(labelDateNaissance);
            fieldDateNaissance = new JTextField();
            fieldDateNaissance.setPreferredSize(new Dimension(250, 30));
            fieldDateNaissance.setText(dateNaiss);
            panel6.add(fieldDateNaissance);
            contenu1.add(panel6);
     
            //form fieldAdresse
            JPanel panel7 = new JPanel();
            panel7.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel labelAdresse = new JLabel("Adresse client:");
            labelAdresse.setPreferredSize(new Dimension(150, 30));
            panel7.add(labelAdresse);
            fieldAdresse = new JTextField();
            fieldAdresse.setPreferredSize(new Dimension(250, 30));
            fieldAdresse.setText(adresse);
            panel7.add(fieldAdresse);
            contenu1.add(panel7);
     
            //form accueil
            JPanel panel8 = new JPanel();
            panel8.setLayout(new FlowLayout(FlowLayout.CENTER));
            accueil = new JButton("Accueil");
            accueil.addActionListener(this);
            panel8.add(accueil);
            contenu1.add(panel8);
     
            //form valider
            panel8.setLayout(new FlowLayout(FlowLayout.CENTER));
            valider = new JButton("Valider");
            valider.addActionListener(this);
            panel8.add(valider);
            contenu1.add(panel8);
     
            //fenetre de confirmation quand clic croix
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    int confirmed = JOptionPane.showConfirmDialog(null, "Voulez-vous quitter la fenêtre sans sauvegarder?", "Quitter création client", JOptionPane.YES_NO_OPTION);
                    if (confirmed == JOptionPane.YES_OPTION) {
                        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    } else {
                        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    }
                }
            });
        }
     
        @Override
        public void actionPerformed(ActionEvent e) {
            String event = e.getActionCommand();
            if (event.equalsIgnoreCase("Valider")) {
                int idClient = Integer.parseInt(fieldId.getText());
                String numNatClient = fieldNumNat.getText();
                String nomClient = fieldNom.getText();
                String prenomClient = fieldPrenom.getText();
                String telClient = fieldTel.getText();
                String mailClient = fieldMail.getText();
                String dateNaissance = fieldDateNaissance.getText();
                String adresseClient = fieldAdresse.getText();
                contr.updateClient(idClient, numNatClient, nomClient, prenomClient, telClient, mailClient, dateNaissance, adresseClient);
                this.setVisible(false);
                dispose();
            }
            if (event.equalsIgnoreCase("Accueil")) {
                int rep = JOptionPane.showConfirmDialog(null, "Voulez-vous quitter la fenêtre sans sauvegarder?", "Quitter création client", JOptionPane.YES_NO_OPTION);
                // Sortie du programme
                if (rep == 0) {
                    //this.setVisible(true);
                    this.setVisible(false);
                }
            }
     
        }
    }

    Mon Controler
    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
    package be.iepscfjemelle.projet_sgbd.controler;
     
    import be.iepscfjemelle.projet_sgbd.vues.FormUpdateClient;
    import be.iepscfjemelle.projet_sgbd.facades.DAOFactory;
    import be.iepscfjemelle.projet_sgbd.model.Client;
    import be.iepscfjemelle.projet_sgbd.model.IntDAO;
    import be.iepscfjemelle.projet_sgbd.vues.PageAccueil;
    import be.iepscfjemelle.projet_sgbd.vues.FormCreateClient;
    import be.iepscfjemelle.projet_sgbd.vues.FormCreateCommande;
    import be.iepscfjemelle.projet_sgbd.vues.TabChoiceClient;
    import be.iepscfjemelle.projet_sgbd.vues.TabUpdateClient;
    import java.beans.PropertyChangeSupport;
    import java.util.ArrayList;
    import java.util.HashSet;
     
    /**
     * Class controler, tout passe par lui
     */
    public class Controler {
     
        /**
         * attributs
         */
        public ArrayList<Client> listClients;
        private TabUpdateClient tabClient;
        private static final Controler INSTANCE = new Controler();
        public PageAccueil pageAccueil;
     
        // création écouteur pour le rafraîchissement des vues (observer)
        private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
     
        /**
         * Constructeur
         */
     
     
        private Controler() {
            this.pageAccueil = new PageAccueil(this);
            pageAccueil.setVisible(true);
        }
     
        /**
         * getInstance, retourne une instance unique de mon controleur
         *
         * @return INSTANCE
         */
        public static Controler getInstance() {
            return INSTANCE;
        }
     
        /**
         * Ajout d"un client
         *
         * @param numeroNational
         * @param nom
         * @param prenom
         * @param tel
         * @param mail
         * @param naissance
         * @param adresse
         */
        public void addClient(String numeroNational, String nom, String prenom, String tel, String mail, String naissance, String adresse) {
            Client client = new Client(numeroNational, nom, prenom, tel, mail, naissance, adresse);
            IntDAO createClient = DAOFactory.getDAO("ClientDAO");
            createClient.create(client);
        }
     
        /**
         * Lecture de tous les clients d'une table
         * @return 
         */
        public ArrayList<Client> loadAllClients() {
            IntDAO createClient = DAOFactory.getDAO("ClientDAO");
            this.listClients = createClient.readAllObject();
            return listClients;   
        }
     
        /**
         * Lecture d'un client sur base de l'id
         *
         * @param id
         * @return client
         */
        public Client loadClientById(int id) {
            Client client = new Client(id);
            IntDAO createClient = DAOFactory.getDAO("ClientDAO");
            client = (Client) createClient.read(id);
            return client;
        }
     
        /**
         * Affiche la table des client avec le bouton "modifier"
         */
        public void showTabUpdateClient() {
            IntDAO lectureClients = DAOFactory.getDAO("ClientDAO");
            this.listClients = lectureClients.readAllObject();
            tabClient = new TabUpdateClient(listClients, this);
            //création d'un listener avec un nom et la classe qui l'implémentera.
            this.pcs.addPropertyChangeListener("Listener Client", tabClient);
            tabClient.setVisible(true);
        }
     
        /**
         * Update d'un client sur base de l'id
         *
         * @param id
         * @param nom
         * @param prenom
         * @param tel
         * @param mail
         * @param naissance
         * @param adresse
         */
        public void updateClient(int id, String numNat, String nom, String prenom, String tel, String mail, String naissance, String adresse) {
            IntDAO createClient = DAOFactory.getDAO("ClientDAO");
            createClient.update(id, numNat, nom, prenom, tel, mail, naissance, adresse);
            // Notification un changement
            this.pcs.firePropertyChange("Listener Client", null, createClient);
        }
     
        /**
         * Delete d'un client sur base de l'id
         *
         * @param id
         */
        public void delClient(int id) {
            IntDAO createClient = DAOFactory.getDAO("ClientDAO");
            createClient.delete(id);
        }
     
        /**
         * Affiche le formulaire de création de client
         */
        public void showFormCreateClient() {
            FormCreateClient formCreateClient = new FormCreateClient(this);
            formCreateClient.setVisible(true);
        }
     
        /**
         * Affiche le formulaire de modification d'un client
         * @param client 
         */
        public void showFormUpdateClient(Client client) {
            //System.out.println(client.adresseClient);
            IntDAO updateClient = DAOFactory.getDAO("ClientDAO");
            updateClient.update(client.idClient, client.numeroNational, client.nomClient, client.prenomClient, 
                    client.telephoneClient, client.mailClient, client.dateNaissanceClient, client.adresseClient);
            FormUpdateClient formUpdateClient = new FormUpdateClient(client.idClient, client.numeroNational, client.nomClient, client.prenomClient, 
                    client.telephoneClient, client.mailClient, client.dateNaissanceClient, client.adresseClient, this);
            formUpdateClient.setVisible(true);
        }
     
     
    }
    ça fait plusieurs jours que je coince sur la façon d'utiliser ce PropertyChangeListener.

    Suis-je dans le bon jusqu'à maintenant?

    Puis-je simplement modifier une ligne de ma JTable avec le client modifier, ou, est ce que je dois travailler à partir d'une liste de client, que je modifie avec le client modifier et que je renvoi à ma JTable?

  2. #2
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Billets dans le blog
    2
    Par défaut
    Salut,

    Il faut notifier la JTable lors de la réception de l'événement de changement. Ce serait plus logique que ça soit le modèle qui écoute les changements. Dans le l'écouteur PropertyChangeListener, il te suffit de trouver la ligne qui contient l'instance de Client, et tu appelles fireTableRowsUpdated, pour notifier la JTable.

    Aussi, il peut être préférable d'utiliser un SwingPropertyChangeSupport qui peut lancer les PropertyChangeEvent dans le thread de Swing (EDT), pour éviter les accès concurrents éventuels.

    Attention aussi à bien implémenter equals/hashCode dans Client (qui doit comparer chaque propriété), sinon l'événement ne sera pas propagé (l'instance de Client n'étant pas recréée mais seulement modifiée).

    Enfin, il peut être intéressant pour optimiser de gérer un événement pour chaque propriété de Client (le PropertyChangeSupport serait géré par Client), et faire des fireTableCellUpdated dans le modèle (il suffit d'enregistrer un écouteur sur chaque instance de Client), éventuellement en faisant un relais vers un SwingPropertyChangeSupport (le client devant être logiquement indépendant de l'UI, donc intégrant un PropertyChangeSupport). Les événements d'ajout et suppression éventuels eux resteraient externes à Client.
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  3. #3
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Septembre 2017
    Messages : 176
    Par défaut
    Merci pour ta réponse.

    Equals et hashcode sont bien présent dans ma class Client.
    Par contre pour le reste, tu aurais un exemple?

  4. #4
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Septembre 2017
    Messages : 176
    Par défaut
    Citation Envoyé par joel.drigo Voir le message
    Salut,

    Il faut notifier la JTable lors de la réception de l'événement de changement. Ce serait plus logique que ça soit le modèle qui écoute les changements. Dans le l'écouteur PropertyChangeListener, il te suffit de trouver la ligne qui contient l'instance de Client, et tu appelles fireTableRowsUpdated, pour notifier la JTable.
    Si je comprends bien la première partie, faire un implements PropertyChangeListener sur mon model ci dessous plutôt que sur ma fenêtre?
    Et l'instance du client serait dans la méthode getValueAt?

    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
    package be.iepscfjemelle.projet_sgbd.vues;
     
    import be.iepscfjemelle.projet_sgbd.model.Client;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import javax.swing.JButton;
    import javax.swing.table.AbstractTableModel;
     
    /**
     * Table modèle avec la colonne et bouton modifier
     *
     */
    public class TabModelUpdateClients extends AbstractTableModel implements PropertyChangeListener{
     
        /**
         * Attributs
         */
        private final ArrayList list;
        private final String[] columnNames = {"id", "numéro national", "Nom", "Prénom", "Téléphone", "Email", "Date de naissance", "Adresse", "Modification"};
     
        /**
         * Constructeur
         *
         * @param list
         */
        public TabModelUpdateClients(ArrayList list) {
            this.list = list;
        }
     
        /**
         * Renvoie un nom par défaut pour la colonne.
         *
         * @param col /nom de colonne
         * @return String
         */
        @Override
        public String getColumnName(int col) {
            return this.columnNames[col];//pour remplacer le switch du projet fin 2ème
        }
     
        /**
         * Retourne le nombre de lignes dans le modèle. Un JTable utilise cette
         * méthode pour déterminer le nombre de lignes à afficher. Cette méthode
         * devrait être rapide, car elle est appelée fréquemment pendant le rendu.
         *
         * @return int
         */
        @Override
        public int getRowCount() {
            if (list == null) {
                return 0;
            } else {
                return list.size();
            }
        }
     
        /**
         * Renvoie le nombre de colonnes du modèle. Un JTable utilise cette méthode
         * pour déterminer le nombre de colonnes à créer et à afficher par défaut.
         *
         * @return int
         */
        @Override
        public int getColumnCount() {
            return columnNames.length;
     
        }
     
        /**
         * Retourne la valeur à l'emplacement spécifié
         *
         * @param rowIndex
         * @param columnIndex
         * @return
         */
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Client client = (Client) list.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return client.getIdClient();
                case 1:
                    return client.getNumeroNational();
                case 2:
                    return client.getNomClient();
                case 3:
                    return client.getPrenomClient();
                case 4:
                    return client.getTelephoneClient();
                case 5:
                    return client.getMailClient();
                case 6:
                    return client.getDateNaissanceClient();
                case 7:
                    return client.getAdresseClient();
            }
            return null;
        }
     
        /**
         * Rend ma colonne 8 éditable (mes boutons Modifier)
         * @param rowIndex
         * @param columnIndex
         * @return 
         */
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if (columnIndex == 8) { //columnIndex: est la colonne que je veux rendre éditable
                return true;
            } else {
                return false;
            }
        }
     
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
     
    }

  5. #5
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Billets dans le blog
    2
    Par défaut
    Un exemple sans PropertyChangeSupport :

    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
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
     
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicInteger;
     
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.AncestorEvent;
    import javax.swing.event.AncestorListener;
    import javax.swing.table.AbstractTableModel;
     
    public class Exemple {
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		Collection<Client> clients = Arrays.asList(
    				new Client("A",42),
    				new Client("B",23),
    				new Client("C",14)
    				);
     
    		ClientTableModel tablemodel = new ClientTableModel(clients);
    		JTable table = new JTable(tablemodel);
    		table.setPreferredScrollableViewportSize(table.getPreferredSize());
    		JPanel panel = new JPanel(new BorderLayout());
    		JScrollPane scrollpane = new JScrollPane(table);
    		scrollpane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    		panel.add(scrollpane);
     
    		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    		JButton editButton = new JButton("Modifier");
    		editButton.setEnabled(false);
    		buttonPanel.add(editButton);
    		panel.add(buttonPanel,BorderLayout.SOUTH);
     
    		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    		table.getSelectionModel().addListSelectionListener(e->editButton.setEnabled(table.getSelectedRowCount()>0));
     
    		editButton.addActionListener(e-> {
    			Client client = tablemodel.getClient(table.getSelectedRow());
    			if ( client!=null && editClient(table, client) ) {
    				tablemodel.updateClient(client);
    			}
    		});
     
    		frame.add(panel);
     
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
     
    	}
     
    	private static boolean editClient(JComponent parentComponent, Client client) {
    		JPanel panel = new JPanel(new GridBagLayout());
    		GridBagConstraints gbc = new GridBagConstraints();
    		gbc.insets = new Insets(5, 5, 5, 5);
    		gbc.gridy=0;
    		gbc.gridx=GridBagConstraints.RELATIVE;
    		gbc.fill=GridBagConstraints.HORIZONTAL;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.NAME+" :"),gbc);
    		JTextField nameField = new JTextField(client.getName(),20);
    		gbc.anchor=GridBagConstraints.EAST;
    		panel.add(nameField,gbc);
    		gbc.gridy=1;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.VALUE+" :"),gbc);
    		gbc.anchor=GridBagConstraints.EAST;
    		JTextField valueField = new JTextField(String.valueOf(client.getValue()),20);
    		panel.add(valueField,gbc);
    		nameField.addAncestorListener(new RequestFocusListener());
     
    		if ( JOptionPane.showConfirmDialog(parentComponent, 
    				panel, 
    				"Editer client " + client.getName(), 
    				JOptionPane.OK_CANCEL_OPTION,
    				JOptionPane.PLAIN_MESSAGE
    				)==JOptionPane.OK_OPTION ) {
    			client.setName(nameField.getText());
    			try {
    				client.setValue(Integer.parseInt(valueField.getText()));
    			}
    			catch (NumberFormatException e) {
    				JOptionPane.showMessageDialog(parentComponent, "Erreur valeur non numérique : " + valueField.getText(), "Erreur", JOptionPane.ERROR_MESSAGE);
    			}
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
     
    	public static class ClientTableModel extends AbstractTableModel {
     
    		public static final String NAME = "Nom";
    		public static final String VALUE = "Valeur";
    		private static String[] COLUMNS = {NAME, VALUE};
    		private List<Client> clients = new ArrayList<>();
     
    		public ClientTableModel(Collection<Client> clients) {
    			if ( clients!=null ) {
    				this.clients.addAll(clients);
    			}
    		}
     
    		public void updateClient(Client client) {
    			int rowIndex = clients.indexOf(client);
    			if ( rowIndex>=0 ) {
    				fireTableRowsUpdated(rowIndex, rowIndex);
    			}
    		}
     
    		public Client getClient(int rowIndex) {
    			if ( rowIndex<clients.size() ) {
    				return clients.get(rowIndex);
    			}
    			return null;
    		}
     
    		@Override
    		public String getColumnName(int columnIndex) {
    			return COLUMNS[columnIndex];
    		}
     
    		@Override
    		public Class<?> getColumnClass(int columnIndex) {
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return String.class;
    			case VALUE:
    				return Integer.class;
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    		@Override
    		public int getRowCount() {
    			return clients.size();
    		}
     
    		@Override
    		public int getColumnCount() {
    			return COLUMNS.length;
    		}
     
    		@Override
    		public Object getValueAt(int rowIndex, int columnIndex) {
    			Client client = clients.get(rowIndex);
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return client.getName();
    			case VALUE:
    				return client.getValue();
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    	}
     
    	public static class Client {
     
    		private String name;
    		private int value;
    		private final String id;
    		private static final AtomicInteger ID_FACTORY=new AtomicInteger();
     
    		public Client(String name, int value) {
    			this.id = String.valueOf(ID_FACTORY.getAndIncrement());
    			this.name=name;
    			this.value=value;
    		}
     
    		public String getId() {
    			return id;
    		}
     
    		public String getName() {
    			return name;
    		}
     
    		public void setName(String name) {
    			this.name=name;
    		}
     
    		public int getValue() {
    			return value;
    		}
     
    		public void setValue(int value) {
    			this.value=value;
    		}
     
    	}
     
    	public static class RequestFocusListener implements AncestorListener {
     
    		public RequestFocusListener() {
    		}
     
    		@Override
    		public void ancestorAdded(AncestorEvent e) {
    			JComponent component = e.getComponent();
    			component.requestFocusInWindow();
    		}
     
    		@Override
    		public void ancestorMoved(AncestorEvent e) {}
     
    		@Override
    		public void ancestorRemoved(AncestorEvent e) {}
     
    	}
     
    }


    Un exemple sans PropertyChangeSupport par row/client :

    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
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
     
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.beans.PropertyChangeSupport;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.atomic.AtomicInteger;
     
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.AncestorEvent;
    import javax.swing.event.AncestorListener;
    import javax.swing.event.SwingPropertyChangeSupport;
    import javax.swing.table.AbstractTableModel;
     
    public class Exemple {
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		Collection<Client> clients = Arrays.asList(
    				new Client("A",42),
    				new Client("B",23),
    				new Client("C",14)
    				);
     
    		ClientTableModel tablemodel = new ClientTableModel(clients);
    		JTable table = new JTable(tablemodel);
    		table.setPreferredScrollableViewportSize(table.getPreferredSize());
    		JPanel panel = new JPanel(new BorderLayout());
    		JScrollPane scrollpane = new JScrollPane(table);
    		scrollpane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    		panel.add(scrollpane);
     
    		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    		JButton editButton = new JButton("Modifier");
    		editButton.setEnabled(false);
    		buttonPanel.add(editButton);
    		panel.add(buttonPanel,BorderLayout.SOUTH);
     
    		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    		table.getSelectionModel().addListSelectionListener(e->editButton.setEnabled(table.getSelectedRowCount()>0));
     
    		editButton.addActionListener(e-> {
    			Client client = tablemodel.getClient(table.getSelectedRow());
    			if ( client!=null ) {
    				Client newClient = editClient(table, client);
    				if ( newClient!=null ) {
    					tablemodel.updateClient(client, newClient);
    				}
    			}
    		});
     
    		frame.add(panel);
     
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
     
    	}
     
    	private static Client editClient(JComponent parentComponent, Client client) {
    		JPanel panel = new JPanel(new GridBagLayout());
    		GridBagConstraints gbc = new GridBagConstraints();
    		gbc.insets = new Insets(5, 5, 5, 5);
    		gbc.gridy=0;
    		gbc.gridx=GridBagConstraints.RELATIVE;
    		gbc.fill=GridBagConstraints.HORIZONTAL;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.NAME+" :"),gbc);
    		JTextField nameField = new JTextField(client.getName(),20);
    		gbc.anchor=GridBagConstraints.EAST;
    		panel.add(nameField,gbc);
    		gbc.gridy=1;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.VALUE+" :"),gbc);
    		gbc.anchor=GridBagConstraints.EAST;
    		JTextField valueField = new JTextField(String.valueOf(client.getValue()),20);
    		panel.add(valueField,gbc);
    		nameField.addAncestorListener(new RequestFocusListener());
    		if ( JOptionPane.showConfirmDialog(parentComponent, 
    				panel, 
    				"Editer client " + client.getName(), 
    				JOptionPane.OK_CANCEL_OPTION,
    				JOptionPane.PLAIN_MESSAGE
    				)==JOptionPane.OK_OPTION ) {
    			String name = nameField.getText();
    			try {
    				int value = Integer.parseInt(valueField.getText());
    				return new Client(name, value);
    			}
    			catch (NumberFormatException e) {
    				JOptionPane.showMessageDialog(parentComponent, "Erreur valeur non numérique : " + valueField.getText(), "Erreur", JOptionPane.ERROR_MESSAGE);
    			}
    		}
    		return null;
    	}
     
    	public static class ClientTableModel extends AbstractTableModel {
     
    		public static final String NAME = "Nom";
    		public static final String VALUE = "Valeur";
    		private static final String CLIENT_PROPERTY = "CLIENT";
    		private static String[] COLUMNS = {NAME, VALUE};
    		private List<Client> clients = new ArrayList<>();
     
    		private PropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this,true);
     
    		public ClientTableModel(Collection<Client> clients) {
    			if ( clients!=null ) {
    				this.clients.addAll(clients);
    			}
    			propertyChangeSupport.addPropertyChangeListener(CLIENT_PROPERTY, e-> {
    				Client oldClient = (Client)e.getOldValue();
    				Client newClient = (Client)e.getNewValue();
    				int rowIndex = ClientTableModel.this.clients.indexOf(oldClient);
    				if ( rowIndex>=0 ) {
    					ClientTableModel.this.clients.set(rowIndex, newClient);
    					fireTableRowsUpdated(rowIndex, rowIndex);
    				}
    			});
    		}
     
    		public void updateClient(Client oldClient, Client newClient) {
    			propertyChangeSupport.firePropertyChange(CLIENT_PROPERTY, oldClient, newClient);
    		}
     
    		public Client getClient(int rowIndex) {
    			if ( rowIndex<clients.size() ) {
    				return clients.get(rowIndex);
    			}
    			return null;
    		}
     
    		@Override
    		public String getColumnName(int columnIndex) {
    			return COLUMNS[columnIndex];
    		}
     
    		@Override
    		public Class<?> getColumnClass(int columnIndex) {
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return String.class;
    			case VALUE:
    				return Integer.class;
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    		@Override
    		public int getRowCount() {
    			return clients.size();
    		}
     
    		@Override
    		public int getColumnCount() {
    			return COLUMNS.length;
    		}
     
    		@Override
    		public Object getValueAt(int rowIndex, int columnIndex) {
    			Client client = clients.get(rowIndex);
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return client.getName();
    			case VALUE:
    				return client.getValue();
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    	}
     
    	public static class Client {
     
    		private String name;
    		private int value;
    		private final String id;
    		private static final AtomicInteger ID_FACTORY=new AtomicInteger();
     
    		public Client(String name, int value) {
    			this.id = String.valueOf(ID_FACTORY.getAndIncrement());
    			this.name=name;
    			this.value=value;
    		}
     
    		public String getId() {
    			return id;
    		}
     
    		public String getName() {
    			return name;
    		}
     
    		public void setName(String name) {
    			this.name=name;
    		}
     
    		public int getValue() {
    			return value;
    		}
     
    		public void setValue(int value) {
    			this.value=value;
    		}
     
    		@Override
    		public int hashCode() {
    			return Objects.hash(id, name, value);
    		}
     
    		@Override
    		public boolean equals(Object obj) {
    			if ( obj instanceof Client ) {
    				Client client = (Client)obj;
    				return Objects.equals(id, client.id) && Objects.equals(name, client.name) && Objects.equals(value, client.value);
    			}
    			else {
    				return false;
    			}
    		}
     
    	}
     
    	public static class RequestFocusListener implements AncestorListener {
     
    		public RequestFocusListener() {
    		}
     
    		@Override
    		public void ancestorAdded(AncestorEvent e) {
    			JComponent component = e.getComponent();
    			component.requestFocusInWindow();
    		}
     
    		@Override
    		public void ancestorMoved(AncestorEvent e) {}
     
    		@Override
    		public void ancestorRemoved(AncestorEvent e) {}
     
    	}
     
    }


    Un exemple sans PropertyChangeSupport par propriétés :

    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
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
     
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.atomic.AtomicInteger;
     
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.AncestorEvent;
    import javax.swing.event.AncestorListener;
    import javax.swing.event.SwingPropertyChangeSupport;
    import javax.swing.table.AbstractTableModel;
     
    public class Exemple {
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		Collection<Client> clients = Arrays.asList(
    				new Client("A",42),
    				new Client("B",23),
    				new Client("C",14)
    				);
     
    		ClientTableModel tablemodel = new ClientTableModel(clients);
    		JTable table = new JTable(tablemodel);
    		table.setPreferredScrollableViewportSize(table.getPreferredSize());
    		JPanel panel = new JPanel(new BorderLayout());
    		JScrollPane scrollpane = new JScrollPane(table);
    		scrollpane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    		panel.add(scrollpane);
     
    		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    		JButton editButton = new JButton("Modifier");
    		editButton.setEnabled(false);
    		buttonPanel.add(editButton);
    		panel.add(buttonPanel,BorderLayout.SOUTH);
     
    		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    		table.getSelectionModel().addListSelectionListener(e->editButton.setEnabled(table.getSelectedRowCount()>0));
     
    		editButton.addActionListener(e-> {
    			Client client = tablemodel.getClient(table.getSelectedRow());
    			if ( client!=null ) {
    				editClient(table, client);
    			}
    		});
     
    		frame.add(panel);
     
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
     
    	}
     
    	private static void editClient(JComponent parentComponent, Client client) {
    		JPanel panel = new JPanel(new GridBagLayout());
    		GridBagConstraints gbc = new GridBagConstraints();
    		gbc.insets = new Insets(5, 5, 5, 5);
    		gbc.gridy=0;
    		gbc.gridx=GridBagConstraints.RELATIVE;
    		gbc.fill=GridBagConstraints.HORIZONTAL;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.NAME+" :"),gbc);
    		JTextField nameField = new JTextField(client.getName(),20);
    		gbc.anchor=GridBagConstraints.EAST;
    		panel.add(nameField,gbc);
    		gbc.gridy=1;
    		gbc.anchor=GridBagConstraints.WEST;
    		panel.add(new JLabel(ClientTableModel.VALUE+" :"),gbc);
    		gbc.anchor=GridBagConstraints.EAST;
    		JTextField valueField = new JTextField(String.valueOf(client.getValue()),20);
    		panel.add(valueField,gbc);
    		nameField.addAncestorListener(new RequestFocusListener());
    		if ( JOptionPane.showConfirmDialog(parentComponent, 
    				panel, 
    				"Editer client " + client.getName(), 
    				JOptionPane.OK_CANCEL_OPTION,
    				JOptionPane.PLAIN_MESSAGE
    				)==JOptionPane.OK_OPTION ) {
    			String name = nameField.getText();
    			try {
    				int value = Integer.parseInt(valueField.getText());
    				client.setName(name);
    				client.setValue(value);
    			}
    			catch (NumberFormatException e) {
    				JOptionPane.showMessageDialog(parentComponent, "Erreur valeur non numérique : " + valueField.getText(), "Erreur", JOptionPane.ERROR_MESSAGE);
    			}
    		}
    	}
     
    	public static class ClientTableModel extends AbstractTableModel {
     
    		public static final String NAME = "Nom";
    		public static final String VALUE = "Valeur";
    		private static String[] COLUMNS = {NAME, VALUE};
    		private List<Client> clients = new ArrayList<>();
     
    		private PropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this,true);
    		private PropertyChangeListener clientPropertyChangeListener;
     
    		public ClientTableModel(Collection<Client> clients) {
    			clientPropertyChangeListener = e-> {
    				switch(e.getPropertyName()) {
    				case Client.NAME:
    					propertyChangeSupport.firePropertyChange(NAME, null, e.getSource());
    					break;
    				case Client.VALUE:
    					propertyChangeSupport.firePropertyChange(VALUE, null, e.getSource());
    					break;
    				}
    			};
    			if ( clients!=null ) {
    				for(Client client : clients) {
    					client.addPropertyChangeListener(clientPropertyChangeListener);
    					this.clients.add(client);
    				}
    			}
    			propertyChangeSupport.addPropertyChangeListener(e-> {
     
    				Client modifiedClient = (Client) e.getNewValue();
    				for(int rowIndex=0; rowIndex<clients.size(); rowIndex++) {
    					if ( ClientTableModel.this.clients.get(rowIndex).getId().equals(modifiedClient.getId()) ) {
    						switch(e.getPropertyName()) {
    						case NAME:
    							fireTableCellUpdated(rowIndex, 0);
    							break;
    						case VALUE:
    							fireTableCellUpdated(rowIndex, 1);
    							break;
    						}
    						break;
    					}
    				}
     
    			});
    		}
     
    		public void uninstallListeners() {
    			for(Client client : clients) {
    				client.removePropertyChangeListener(clientPropertyChangeListener);
    			}
    		}
     
    		public Client getClient(int rowIndex) {
    			if ( rowIndex<clients.size() ) {
    				return clients.get(rowIndex);
    			}
    			return null;
    		}
     
    		@Override
    		public String getColumnName(int columnIndex) {
    			return COLUMNS[columnIndex];
    		}
     
    		@Override
    		public Class<?> getColumnClass(int columnIndex) {
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return String.class;
    			case VALUE:
    				return Integer.class;
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    		@Override
    		public int getRowCount() {
    			return clients.size();
    		}
     
    		@Override
    		public int getColumnCount() {
    			return COLUMNS.length;
    		}
     
    		@Override
    		public Object getValueAt(int rowIndex, int columnIndex) {
    			Client client = clients.get(rowIndex);
    			switch(COLUMNS[columnIndex]) {
    			case NAME:
    				return client.getName();
    			case VALUE:
    				return client.getValue();
    			default:
    				throw new IllegalStateException();
    			}
    		}
     
    	}
     
    	public static class Client {
     
    		public static final String NAME = "NAME";
    		public static final String VALUE = "VALUE";
     
    		private String name;
    		private int value;
    		private final String id;
    		private static final AtomicInteger ID_FACTORY=new AtomicInteger();
    		private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
     
    		public Client(String name, int value) {
    			this.id = String.valueOf(ID_FACTORY.getAndIncrement());
    			this.name=name;
    			this.value=value;
    		}
     
    		public String getId() {
    			return id;
    		}
     
    		public String getName() {
    			return name;
    		}
     
    		public void setName(String name) {
    			String old = this.name;
    			this.name=name;
    			propertyChangeSupport.firePropertyChange(NAME, old, name);
    		}
     
    		public int getValue() {
    			return value;
    		}
     
    		public void setValue(int value) {
    			int old = this.value;
    			this.value=value;
    			propertyChangeSupport.firePropertyChange(VALUE, old, value);
    		}
     
    		@Override
    		public int hashCode() {
    			return Objects.hash(id, name, value);
    		}
     
    		@Override
    		public boolean equals(Object obj) {
    			if ( obj instanceof Client ) {
    				Client client = (Client)obj;
    				return Objects.equals(id, client.id) && Objects.equals(name, client.name) && Objects.equals(value, client.value);
    			}
    			else {
    				return false;
    			}
    		}
     
    		public void addPropertyChangeListener(PropertyChangeListener listener) {
    			propertyChangeSupport.addPropertyChangeListener(listener);
    		}
     
    		public void removePropertyChangeListener(PropertyChangeListener listener) {
    			propertyChangeSupport.removePropertyChangeListener(listener);
    		}
     
    		public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
    			propertyChangeSupport.addPropertyChangeListener(name, listener);
    		}
     
    		public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
    			propertyChangeSupport.removePropertyChangeListener(name, listener);
    		}
     
    	}
     
    	public static class RequestFocusListener implements AncestorListener {
     
    		public RequestFocusListener() {
    		}
     
    		@Override
    		public void ancestorAdded(AncestorEvent e) {
    			JComponent component = e.getComponent();
    			component.requestFocusInWindow();
    		}
     
    		@Override
    		public void ancestorMoved(AncestorEvent e) {}
     
    		@Override
    		public void ancestorRemoved(AncestorEvent e) {}
     
    	}
     
    }
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  6. #6
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Septembre 2017
    Messages : 176
    Par défaut
    Résolu, j'envoi une nouvelle liste à ma table plutôt qu'un Objet Client et implémentation de la méthode propertyChange


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /**
         * Affiche la table des client avec le bouton "modifier"
         */
        public void showTabUpdateClient() {
            IntDAO lectureClients = DAOFactory.getDAO("ClientDAO");
            this.listClients = lectureClients.readAllObject();
            tabClient = new TabUpdateClient(listClients, this);
            //création d'un listener avec un nom et la classe qui l'implémentera.
            this.pcs.addPropertyChangeListener("Listener Client", tabClient);
            tabClient.setVisible(true);
        }
    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
    /**
         * Lancement d'un changement suite à une notification d'un listener
         * @param evt 
         */
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("Listener Client")) {
                ArrayList listClientNew = (ArrayList) evt.getNewValue();
                this.tableau.setModel(new TabModelUpdateClients(listClientNew));
                this.tableau.getColumnModel().getColumn(7).setMaxWidth(0);
                this.tableau.getColumnModel().getColumn(7).setMinWidth(0);
                this.tableau.getColumnModel().getColumn(7).setPreferredWidth(0);
     
                TableButton button = new TableButton() {
                    private static final long serialVersionUID = 1L;
     
                    protected String getButtonText(JTable table, Object value,
                            boolean isSelected, boolean hasFocus, int row, int column) {
                        return String.valueOf(value);
                    }
                    //pas utilisé ici
     
                    protected void actionPerformed(JTable table, Object value, int row,
                            int column) {
                        //System.out.println("Action sur ligne " + row + " et colonne " + column);   
                    }
                };
                // boutton sur la colonne 8
                button.install(tableau, 8);
            }
        }

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

Discussions similaires

  1. Problème avec JTable
    Par reeda dans le forum Composants
    Réponses: 5
    Dernier message: 03/10/2008, 18h06
  2. Problème avec JTable
    Par syrius31 dans le forum Composants
    Réponses: 5
    Dernier message: 26/07/2007, 11h01
  3. Problème de conversion String en Float avec JTable
    Par dumasan dans le forum Composants
    Réponses: 4
    Dernier message: 23/04/2007, 11h56
  4. Problème avec Jtable
    Par @yoyo dans le forum Composants
    Réponses: 4
    Dernier message: 22/03/2006, 15h51
  5. problème avec Jtable
    Par magic001 dans le forum Composants
    Réponses: 6
    Dernier message: 15/03/2006, 23h49

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