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

  1. #21
    Membre régulier
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    Pour aider , j'ai réussi à faire une class JTable simple qui renvoi correctmeent le numéro de la ligne et effectuer l'action du click un seul fois ...
    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
    package Carte;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
     
    public class Table extends JFrame{
     
      JTextArea txt = new JTextArea(4, 20);
      // The TableModel controls all the data:
      JTable table;
      public Table()
      {
    	  this.setSize(200,200);
    	  Container cp = getContentPane();
    	    table = new JTable(new DataModel());
    	    cp.add(new JScrollPane(table));
    	    cp.add(BorderLayout.SOUTH, txt);
     
    	    table.addMouseListener(new MouseListener(){
                public void mouseClicked(MouseEvent evt){
     
                	System.out.println(table.getSelectedRow());
                }
        	 public void mouseEntered(MouseEvent er){}                   
             public void mouseExited(MouseEvent ep){}                   
             public void mousePressed(MouseEvent ek){}
             public void mouseReleased(MouseEvent ee){}   
             });
      }
     
      class DataModel extends AbstractTableModel {
        Object[][] data = {
          {"one", "two", "three", "four"},
          {"five", "six", "seven", "eight"},
          {"nine", "ten", "eleven", "twelve"},
        };
        // Prints data when table changes:
        class TML implements TableModelListener {
          public void tableChanged(TableModelEvent e){
            txt.setText(""); // Clear it
            for(int i = 0; i < data.length; i++) {
              for(int j = 0; j < data[0].length; j++)
                txt.append(data[i][j] + " ");
              txt.append("\n");
            }
     
          }
        }
        public DataModel() {
          addTableModelListener(new TML());
        }
        public int getColumnCount() { 
          return data[0].length; 
        }
        public int getRowCount() { 
          return data.length;
        }
        public Object getValueAt(int row, int col) {
          return data[row][col]; 
        }
        public void 
        setValueAt(Object val, int row, int col) {
          data[row][col] = val;
          // Indicate the change has happened:
          fireTableDataChanged();
        }
        public boolean 
        isCellEditable(int row, int col) { 
          return true; 
        }
      }
     
      public static void main(String[] args) {	  
        new Table();
      }
    } ///:~

  2. #22
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    J'ai pas lu toute la discussion, juste le début, mais si tu veux récupérer la ligne ou la cellule sur laquelle tu a cliqué, utilises ce que je fais pour le tooltip de ma JTable :
    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
     
     
    	/**
             * ToolTip is the value of the cell on which is the mouse.
             */
    	public String getToolTipText(MouseEvent e) {
    		Point p = e.getPoint();
    		int row = rowAtPoint(p);
    		int col = columnAtPoint(p);
     
    		String tip = (String) getValueAt(row, col);
    		if (tip != "") //$NON-NLS-1$
    			return tip;
    		else { 
    			return null;
    		}
        }
    En espérant que ça t'aide un peu...

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

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    j'obtiens null en cliquant sur une cellule avec ta méthode ,
    apres avoir essayé pleins de méthode je pense que mon code de tableau est vérolé , mais je vois pas où , a l'aide

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

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    Est ce que mon code dans la réponse 18 est correct ?

  5. #25
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    Citation Envoyé par arsenik7
    j'obtiens null en cliquant sur une cellule avec ta méthode ,
    apres avoir essayé pleins de méthode je pense que mon code de tableau est vérolé , mais je vois pas où , a l'aide
    S'il n'y a rien dans ta cellule, c'est normal
    Sinon, ton code est bien vérolé...

  6. #26
    Membre régulier
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    Alors il est vérolé , rofl

  7. #27
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    Citation Envoyé par arsenik7
    Est ce que mon code dans la réponse 18 est correct ?
    Je ne suis pas sûr, mais cette partie me semble suspecte :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
        class TML implements TableModelListener {
          public void tableChanged(TableModelEvent e){
            txt.setText(""); // Clear it
            for(int i = 0; i < data.length; i++) {
              for(int j = 0; j < data[0].length; j++)
                txt.append(data[i][j] + " ");
              txt.append("\n");
            }
     
          }
        }
    Parce que lorsque ton model va changer, tu ne feras qu'afficher les données qu'il contient, tu ne propageras pas l'évènement.
    Essaie de rajouter en début de méthode, et si ça ne marche pas, voici un model que j'ai créé et qui fonctionne bien :
    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
     
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = {"A", "B", "C", "D","E"};
              private ArrayList data;
     
     
              public MyTableModel() {
    //             super();
                   data = new ArrayList(1);
              }
     
              /**
              * Supprime une ligne du tableau.
              * @param int row : le numéro de la ligne à supprimer.
              */
              public void removeRow(int row) {
                   if (data.size() > 0 && row < data.size()){
                        data.remove(row);
                   }
                   fireTableDataChanged();
                   centerTable();
              }
     
              /**
              * Ajoute une ligne à la fin du tableau.
              * @param Object[] row : les données de la ligne à ajouter.
              */
              public void addRow(Object[] row) {
                   if (row != null && row.length > 0) {
                        data.add(row);
                        fireTableDataChanged();
                   }
              }
     
              /**
              * Remplace les données du tableau.
              * @param ArrayList newData : les nouvelles données à afficher.
              */
              public void setData(ArrayList newData) {
                   data = newData;
                   fireTableDataChanged();
              }
     
              public int getColumnCount() {
                   return columnNames.length;
              }
     
              public int getRowCount() {
                   return data.size();
              }
     
              public String getColumnName(int col) {
                   return columnNames[col];
              }
     
              public Object getValueAt(int row, int col) {
                   return ((Object[])data.get(row))[col];
              }
     
              /*
              * JTable uses this method to determine the default renderer/
              * editor for each cell.  If we didn't implement this method,
              * then the last column would contain text ("true"/"false"),
              * rather than 
              */
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
              }
     
               /*
              * Don't need to implement this method unless your table's
              * data can change.
              */
              public void setValueAt(Object value, int row, int col) {
    //TODO : à décommenter si tu veux afficher les changements...
    //        	boolean DEBUG = true; 
    //            if (DEBUG) {
    //				System.out.println("Setting value at " + row + "," + col 
    //						+ " to " + value + " (an instance of " 
    //						+ value.getClass() + ")"); 
    //			}
     
                   ((Object[])data.get(row))[col] = value;
     
                   // fireTableCellUpdated(row, col);
    //TODO : à décommenter si tu veux afficher les changements...
    //			if (DEBUG) {
    //				System.out.println("New value of data:");
    //				printDebugData();
    //			}
            }
     
              private void printDebugData() {
                   int numRows = getRowCount();
                   int numCols = getColumnCount();
     
                   for (int i=0; i<numRows; i++) {
                        System.out.print("    row " + i + ":"); 
                        for (int j=0; j<numCols; j++) {
                             // System.out.print(" " + data[i][j]);
    					System.out.print("  " + ((Object[])data.get(i))[j]); 
                        }
                        System.out.println();
                   }
                   System.out.println("--------------------------");
              }
     
              public int getMaxLength(){
                   int res = -1;
                   for (int i=0; i<data.size(); i++) {
                        for (int j=0; j<((Object[])data.get(i)).length; j++) {
                             res = Math.max(res,((Object[])data.get(i))[j].toString().length());
                        }
                   }
     
                   return res;
              }
     
    // /*
    // * Don't need to implement this method unless your table's
    //	     * editable.
    //	     */
    //	    public boolean isCellEditable(int row, int col) {
    //	        //Note that the data/cell address is constant,
    //	        //no matter where the cell appears onscreen.
    //	        if (col < 2) {
    //	            return false;
    //	        } else {
    //	            return true;
    //	        }
    //	    }
    	}

  8. #28
    Membre régulier
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    Gasp ! ca se complique , bon je comprends plus
    grand chose là , il me faut un cours

  9. #29
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    Qu'est ce que tu ne comprends pas? Mon model?
    C'est la même chose que ton DataModel, sauf que j'utilise une ArrayList au lieu d'un Object[][] pour stocker mes données (ce qui est plus pratique pour l'ajout et la suppression dynamique de lignes)

    Si t'as essayé et que ça ne marche pas, jette un oeil au tuto Sun

  10. #30
    Membre régulier
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    318
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2005
    Messages : 318
    Points : 99
    Points
    99
    Par défaut
    ENFIN merci pour le tuto SUN , j'ai réussi à obtenir le numéro d la ligne selectionnée :

    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
     
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ...
    //Ask to be notified of selection changes.
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            //Ignore extra messages.
            if (e.getValueIsAdjusting()) return;
     
            ListSelectionModel lsm =
                (ListSelectionModel)e.getSource();
            if (lsm.isSelectionEmpty()) {
                ...//no rows are selected
            } else {
                int selectedRow = lsm.getMinSelectionIndex();
                ...//selectedRow is selected
            }
        }
    });

+ Répondre à la discussion
Cette discussion est résolue.
Page 2 sur 2 PremièrePremière 12

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