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

Composants Java Discussion :

Action sur un JTable


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Par défaut Action sur un JTable
    Bonjour ,

    je cherche à effectuer une action différente selon la ligne (ou la case) cliqué sur mon Jtable. Pour l'instant je ne peux que'effectuer une action pour un clic sur l'ensemble du tableau.
    Merci

  2. #2
    Membre chevronné Avatar de schniouf
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Décembre 2003
    Messages
    382
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Luxembourg

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Décembre 2003
    Messages : 382
    Par défaut
    Utilise l'interface ListSelectionListener :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    	JTable t = new JTable() ;
    	t.getSelectionModel().addListSelectionListener( new MonListener() ) ;
     
    	public class MonListener implements ListSelectionListener
    	{
    		public void valueChanged(ListSelectionEvent e) {
    			int ligneSelectionne = t.getSelectedRow() ;
    			System.out.println("Ligne sélectionnée : " + ligneSelectionne );
    		}
    	}
    Seul soucis, quand on fait un clic sur une ligne, la méthode valueChanged est appelée 2 fois, une fois à l'enfoncement du bouton de la souris et une fois à son relâchement... quelqu'un sait pourquoi ? Sinon le changement de ligne avec les flèches du clavier marche très bien.
    En espérant que ça t'aidera

  3. #3
    Membre éclairé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Par défaut
    Mille merci , je reviendrai te dire ce qu'il en ai.

  4. #4
    Membre éclairé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Par défaut
    il me renvoi -1 sur la première ligne , rofl
    et vrai l'action se fait 2 fois , quelqu'un à une idée ?

  5. #5
    Membre éclairé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Par défaut
    Voilà mon code
    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
    package Carte;
    import java.awt.GridLayout;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.TableCellRenderer;
     
    import Utilitaires.DataBase;
     
    public class Serveurs extends JPanel implements Runnable{
     
    	private static final long serialVersionUID = 1L;
    	String NomServeur;
    	Vector <String> LettreDisque;
    	Vector <Double> tailleMax;
    	Vector <Boolean> unite;
    	int pourcentage;
    	int x = 0;
    	int y = 20;
            JScrollPane pan;
            JTable tabler;
    	DataBase base;
            ResultSet resultat;
            CompTableCellRenderer composant = new CompTableCellRenderer();
            Thread tache;
            JPanel serv = this;
            boolean test = true;
            double taille;
     
     
     
            public void run(){
                while(test){
                    try{
                        this.lancer();
                        this.updateUI();
                        Thread.sleep(60000);
                    }
                    catch(Exception ecx){
                    System.out.println("Erreur de sleep de SErveur"+ecx.fillInStackTrace());}
                }
            }
     
     
            public void stopper(){
                test = false;
            }
     
     
     
     
            public void lancer(){
                try{
                	String req="select id from appareils where nom = '"+NomServeur+"'";
                	System.out.println(req);
    		base = new DataBase(req);
    		base.readBDD();
    		resultat = base.retourner();
    		if(resultat.next() && resultat.next()){
    			String id = resultat.getString("id");
                String[] nom = {"Disque","Espace Libre","Espace Libre","Etat"}; 
     
                LettreDisque = new Vector<String>();
                tailleMax = new Vector<Double>();
                unite = new Vector<Boolean>();
     
                String req1="select lettre_disque,taille from el_disques where superviser = 1 and nom = '"+NomServeur+"' order by lettre_disque";
                System.out.println(req1);
                base.request=req1;
                base.readBDD();
                resultat = base.retourner();
                while(resultat.next()){
                    LettreDisque.addElement(resultat.getString("lettre_disque"));
                    tailleMax.addElement(resultat.getDouble("taille"));
                }
                base.fermer();
                Object[][] data = new Object[LettreDisque.size()][nom.length];
     
     
                JTable table = new JTable(new Modele(data,nom));
                table.setRowHeight(25);
                table.setShowGrid(false);
                new ModeleListener(table);
                pan = new JScrollPane(table);
                for(int i = 0;i < LettreDisque.size();i++){
                	String req2="select probleme,id from erreurs where nom = '"+NomServeur+"' and probleme = '"+LettreDisque.get(i)+"' and critique = 1 and id = '"+id+"'";
                	System.out.println(req2);
                        base = new DataBase(req2);
                        base.readBDD();
                        resultat = base.retourner();
                        if(resultat.next()){
                            table.setValueAt(new ImageIcon("images/iconefalse.GIF"),i,3);
                        }
                        else{
                            table.setValueAt(new ImageIcon("images/iconeOK.GIF"),i,3);
                        }
                        base.fermer();
                        taille = Double.parseDouble(tailleMax.get(i).toString());
                        JProgressBar bar = new JProgressBar(0,(int)taille);
                        System.out.println("taille barre"+taille);
                        String baf="select disques.utiliser from appareils,disques where appareils.id = disques.id and appareils.id = (select max(id) from appareils where nom = '"+NomServeur+"') and description = '"+LettreDisque.get(i).toString()+"' and disques.nom = '"+NomServeur+"' and appareils.id > '"+id+"' order by description";
                        System.out.println(baf);
                        base = new DataBase(baf);
                        base.readBDD();
                        resultat = base.retourner();
                        if(resultat.next()){
                            double utiliser = resultat.getDouble("utiliser");
                           System.out.println(utiliser+","+taille);
                            bar.setValue((int)(taille - utiliser));
                            bar.setString(Integer.toString(100*((int)(taille - utiliser))/(int)taille)+ " % ");
                            bar.setStringPainted(true);
                            table.setValueAt(" "+LettreDisque.get(i).toString(),i,0);
                            table.getColumnModel().getColumn(0).setCellRenderer(composant);
                            table.setValueAt(bar,i,1);
                            table.getColumnModel().getColumn(1).setCellRenderer(composant);
                            table.getColumnModel().getColumn(2).setCellRenderer(composant);
                            if(taille-utiliser < 1){
                                table.setValueAt(" " + Double.toString((taille-utiliser)*1024).substring(0,5)+" Mo/"+String.valueOf(taille*1024).substring(0, 5)+" Mo",i,2);
                                unite.addElement(false);
                            }
                            else{
                                table.setValueAt(" " + Double.toString((taille-utiliser)).substring(0,5)+" Go/"+String.valueOf(taille).substring(0, 5)+" Go",i,2);
                                unite.addElement(true);
                            }
     
    //                        for(int h=0;h<unite.size();h++)
    //                        	System.out.println(unite.elementAt(h));
                        }
                        base.fermer(); 
                    }
    		tabler = table;
                }
    		}
                catch(SQLException sqle){
                	System.out.println("Erreur SQL de la methode lancer");
                sqle.printStackTrace();}
            }
     
     
     
          public Serveurs(String Nom){
                this.NomServeur = Nom;
                this.lancer();
                add(pan);
                setLayout(new GridLayout(1,1));
     
                SelectionListener listener = new SelectionListener(tabler);
                tabler.getSelectionModel().addListSelectionListener(listener);
                tabler.getColumnModel().getSelectionModel().addListSelectionListener(listener);
     
                tabler.setRowSelectionAllowed(true);
                tabler.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            }
     
          class CompTableCellRenderer extends JPanel implements TableCellRenderer{ 
        	  private static final long serialVersionUID = 1L;
                private JProgressBar barre;
    	    public CompTableCellRenderer(){}  
     
     
    	    public JComponent getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row, int column){
                    if(column == 1){
                        barre = (JProgressBar)value;
                        return barre;
                    }
                    else{
                        return new JLabel(value.toString());
                    } 
                }
          }
     
     
    public class SelectionListener implements ListSelectionListener {
              JTable table;
     
              // It is necessary to keep the table since it is not possible
              // to determine the table from the event's source
              SelectionListener(JTable table) {
                  this.table = table;
              }
              public void valueChanged(ListSelectionEvent e) {
            	  int sel=-1;
                  // If cell selection is enabled, both row and column change events are fired
            	  if (e.getSource() == table.getSelectionModel()
                          && table.getRowSelectionAllowed()) {
                        // Column selection changed
                       sel = e.getFirstIndex();
            	  } else if (e.getSource() == table.getColumnModel().getSelectionModel()
                          && table.getColumnSelectionAllowed() ){
                       // Row selection changed
                       sel = e.getFirstIndex();
                   }
     
     
                  System.out.println("SELECTION         "+sel);
                      try{                      
                          JProgressBar barre=null;
                          String lab=null;
     
                          //on créer une nouvelle fenetre pour le disques
                                 barre = (JProgressBar)tabler.getValueAt(sel,1);
                                 lab = tabler.getValueAt(sel,0).toString();
                                 lab = lab.substring(1,3);                          
                                 new DessinEspaceLibre(NomServeur,lab,tailleMax.elementAt(sel),sel,unite.elementAt(sel));   
                          }
                          catch(Exception exsc){
                          	System.out.println("Erreur dans nouveau DessinEspaceLibre");
                          exsc.printStackTrace();}
     
                  if (e.getValueIsAdjusting()) {
                      System.out.println("TEST Adjusting...");
                  }
              }
          }
     
    }

  6. #6
    Membre éclairé Avatar de nicotine002
    Profil pro
    Inscrit en
    Décembre 2005
    Messages
    577
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2005
    Messages : 577
    Par défaut
    Bonjour,

    Je crois que j'avais déjà eut le coup, à la deuxième action, il te renvoie la bonne valeur de la ligne non?

    Si c'est çà, tu met juste un :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
     
     
    JTable t = new JTable() ;
    	t.getSelectionModel().addListSelectionListener( new MonListener() ) ;
     
    	public class MonListener implements ListSelectionListener
    	{
    		public void valueChanged(ListSelectionEvent e) {
    			int ligneSelectionne = t.getSelectedRow() ;
    			if(ligneSelectionne>=0)
                                 System.out.println("Ligne sélectionnée : " + ligneSelectionne );
    		}
    	}

  7. #7
    Membre éclairé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Par défaut
    ligneSelectionne n'est jamais >= 0

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

Discussions similaires

  1. Ajout JTable à un panneau dans une action sur un item
    Par rannou2609 dans le forum Composants
    Réponses: 1
    Dernier message: 21/04/2011, 20h53
  2. Pb Action sur un jbutton dans un jtable
    Par snay13 dans le forum Composants
    Réponses: 6
    Dernier message: 20/07/2010, 00h32
  3. [JTable] Action sur JButton après mise en attente
    Par 6ix dans le forum Composants
    Réponses: 2
    Dernier message: 28/02/2008, 07h27
  4. Action sur une jtable
    Par Karim93210 dans le forum Composants
    Réponses: 3
    Dernier message: 16/07/2007, 10h53
  5. [Flash MX] Action sur un bouton
    Par WriteLN dans le forum Flash
    Réponses: 9
    Dernier message: 20/10/2003, 14h01

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