Jtabel

Résolu
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 - 21 nov. 2008 à 21:56
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 - 13 déc. 2008 à 21:10
salut,
alors dans laffichage de mon jtable les noms de colonnes ne saffichent pas?
ke dois je faire;
merci

 

18 réponses

uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
22 nov. 2008 à 14:53
Nous trouvons toutes les infos dans le JTable Tutorial de Sun:
Adding a Table to a Container:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#show
3
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
24 nov. 2008 à 21:05
Les entêtes de colonnes s'affichent bien chez moi. "DefaultRowSorter" peut accepter des filtres pour les lignes. Il filtre à l'aide d'un "RowFilter" que l'on spécifie en utilisant la méthode "setRowFilter". "RowFilter" décide dans sa méthode "include" par ligne, quelles lignes doivent être affichées. Un "RowFilter" est utile p.ex. pour une fonction de recherche: aussitôt que l'utilisateur tape quelque chose dans un champs de texte, le "RowFilter" ne permet plus que les données qui correspondent au texte introduit.
3
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
24 nov. 2008 à 21:48
Voici un petit exemple:

/*
 * TableTest1.java
 *
 */

import java.awt.BorderLayout;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TableTest1 extends JFrame implements DocumentListener {

    private JTable table;
    private ArrayList<Client> clients;
    private MyTableModel model;
    private JTextField critere;
    private JToolBar toolBar;

    public TableTest1() {
        super("TableTest1");
        initComponents();
        clients = new ArrayList<Client>();
        clients.add(new Client("1", "Andre", "rue du Camping 1", "Mersch", "7572", "visa"));
        clients.add(new Client("2", "Paul", "rue des champs 1", "Lintgen", "7573", "domiciliation"));
        clients.add(new Client("3", "Arnaud", "rue de Mersch 1", "Rollingen", "7574", "visa"));
        clients.add(new Client("4", "Christophe", "rue du Camping 3", "Mersch", "7572", "cash"));
        clients.add(new Client("5", "Jean", "rue du Camping 44", "Mersch", "7572", "domiciliation"));
        clients.add(new Client("6", "Pierre", "rue du Camping 21", "Mersch", "7572", "visa"));
        clients.add(new Client("7", "Marie", "rue du Camping 9", "Mersch", "7572", "virement"));
        clients.add(new Client("8", "Jeanne", "rue du Camping 56", "Mersch", "7572", "cash"));
        clients.add(new Client("9", "Juliette", "rue du Camping 7", "Mersch", "7572", "virement"));
        model = new MyTableModel(clients);
        table.setModel(model);
    }

    private void initComponents() {
        critere = new JTextField();
        table = new JTable();
        toolBar = new JToolBar();
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        table.setAutoCreateRowSorter(true);
        toolBar.add(new JLabel("Critère: mode de paiement: "));
        toolBar.add(critere);
        getContentPane().add(toolBar, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
        setSize(800, 300);
        setLocationRelativeTo(null);
        critere.getDocument().addDocumentListener(this);
    }

    public static void main(final String[] args) {
        Runnable gui = new Runnable() {

            public void run() {
                new TableTest1().setVisible(true);
            }
        };
        //GUI must start on EventDispatchThread:
        SwingUtilities.invokeLater(gui);
    }

    public void insertUpdate(final DocumentEvent e) {
        check();
    }

    public void removeUpdate(final DocumentEvent e) {
        check();
    }

    public void changedUpdate(final DocumentEvent e) {
        check();
    }

    private void check() {
        ((DefaultRowSorter) table.getRowSorter()).setRowFilter(new RowFilter() {

            @Override
            public boolean include(final Entry entry) {
                String v = (String) entry.getValue(5);
                if (v == null) {
                    return true;
                }
                return v.contains(critere.getText());
            }
        });
    }
}

class MyTableModel extends AbstractTableModel {

    private String[] headers = {"id", "nom", "adresse", "ville", "code", "mode"};
    private Object[][] data;

    public MyTableModel(final List<Client> l) {
        data = new Object[l.size()][headers.length];
        remplirMatrice(l);
    }

    public int getColumnCount() {
        return headers.length;
    }

    @Override
    public void setValueAt(final Object o, final int ligne, final int colonne) {
        data[ligne][colonne] = o;
        fireTableCellUpdated(ligne, colonne);
    }

    @Override
    public boolean isCellEditable(final int l, final int c) {
        return true;
    }

    @Override
    public Class getColumnClass(final int c) {
        return headers[c].getClass();
    }

    @Override
    public String getColumnName(final int col) {
        return headers[col].toString();
    }

    //declaration du matrice
    public void remplirMatrice(final List<Client> l) {
        int i = 1;
        data = new Object[1 + l.size()][getColumnCount()];
        while (i < (l.size())) {
            for (Client cl : l) {
                data[i][0] = cl.getId();
                data[i][1] = cl.getNom();
                data[i][2] = cl.getAdresse();
                data[i][3] = cl.getVille();
                data[i][4] = cl.getCode();
                data[i][5] = cl.getModedepaiement();
                i++;
            }
        }
    }

    public void dump() {
        for (int i = 0; i < data.length; i++) {
            System.out.print("|");
            for (int j = 0; j < data[0].length; j++) {
                System.out.print(data[i][j] + "|");
            }
            System.out.println();
        }
    }

    public int getRowCount() {
        return data.length;
    }

    public Object getValueAt(final int rowIndex, final int columnIndex) {
        return data[rowIndex][columnIndex];
    }
}
3
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
29 nov. 2008 à 16:34
Si isCellEditable renvoie "true", la cellule correspondate est modifiable et nous pouvons entrer une nouvelle valeur. La méthode setValueAt reçoit cette valeur et nous pouvons modifier les données. Pour finir, nous appelons la méthode fireTableCellUpdated qui actualise l'affichage des données. Nous trouvons encore plus d'infos dans le tutorial JTable de Sun:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
3

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
5 déc. 2008 à 05:38
"ces trucs la" devraient fontionner. Si ça ne fonctionne pas chez toi, alors fais-nous un court exemple indépendant et exécutable pour nous montrer exactement le problème.
3
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
23 nov. 2008 à 02:15
slt,
merci
bien pour linformation moi jai deja visité ce site est mon code est pafait mais je c pas le probleme d'affichage de noms de colonne alors es ce que que je peux avoir une idée sur la selection par critere????
0
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
23 nov. 2008 à 11:49
Je ne comprends pas ta question. As-tu essayé un des exemples de Sun? Est'ce que tu vois les entêtes des colonnes quand tu exécute un de ces exemples?
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
24 nov. 2008 à 19:43
public class MyTableModel extends AbstractTableModel
{


private String[]headers= {"id","nom","adresse","ville","code","mode"};

private Object[][] data ;


public MyTableModel(List<Client> l )
{
data= new Object[l.size()][headers.length];
remplirMatrice(l);
//getColumnName(6);

}


public int getColumnCount()
{
return headers.length;
}


public void setValueAt(Object o, int ligne, int colonne)
{
data[ligne][colonne]=o;
fireTableCellUpdated(ligne, colonne);
}


public boolean isCellEditable (int l ,int c)
{
return true;
}



public Class getColumnClass(int c)
{
return headers[c].getClass();
}

//declaration du matrice

public String getColumnName(int col)
{
return headers[col].toString();
}



public void remplirMatrice(List<Client> l)
{
int i=1;
data= new Object[1+l.size()][getColumnCount()];
while(i<(l.size()))
{
//cl.afficheC();


for (Client cl:l){
cl.afficheC();

data[i][0]=cl.getId();
data[i][1]=cl.getNom();
data[i][2]=cl.getAdresse();
data[i][3]=cl.getVille();
data[i][4]=cl.getCode();
data[i][5]=cl.getModedepaiement();
i++;
}
}
}


public void dump()
{
for (int i = 0; i < data.length; i++)
{
System.out.print("|");
for (int j = 0; j < data[0].length; j++)
{
System.out.print(data[i][j] + "|");
}
System.out.println();
}
}




public int getRowCount()
{
// TODO Auto-generated method stub
return data.length;
}


public Object getValueAt(int rowIndex, int columnIndex)
{
// TODO Auto-generated method stub
return data[rowIndex][columnIndex];
}

Voila cé mon code et je c pas pk les entetes des colonnes
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
24 nov. 2008 à 19:45
slt,
dsl jé pas terminé jvous dis pk les entetes de colonnes ne saffichent pas ? en principe le code est bon.AINSI je vous demande comment je peux faire une selection par un critere par exemple afficher les clients qui leurs mode de paeiment est visa cé suivant un critere disant
merci pk pour votre reponse monsieur
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
24 nov. 2008 à 21:39
merci bien je v essayer avec cette solution
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
25 nov. 2008 à 01:55
merci bp pour votre aide monsieur
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
28 nov. 2008 à 22:31
alors jé utilisé la criteria voila
public class HibernateCriteriaQueryExample
{


public static List<Client> selectClientCritere(String crtiter){
Session session = HibernatUtil.currentSession();


Criteria criteria = session.createCriteria(Client.class)
.add(Restrictions.eq(crtiter, 123));
List<Client> Clients = criteria.list();
return Clients;
}
puis pour laffichage de tableau jé fais
private JTable getJTable() {
if (jTable == null) {
jTable = new JTable(new MyTableModel(HibernateCriteriaQueryExample.selectClientCritere("Code")));
}
return jTable;
}

mnt je v recupere le critere d'un jcombobox et la valeur de jtextfield en principe je v utilier le getSelectedItem() .alors il faut que je fais une liste pour le jcombobox pour enter les champs?? et comment je peux faire une jtable dynamique ou editable ??? pouvez vous m'aider
0
uhrand Messages postés 491 Date d'inscription samedi 20 mai 2006 Statut Membre Dernière intervention 15 juillet 2012 9
29 nov. 2008 à 03:30
Pour faire une JTable éditable, nous pouvons implémenter les méthodes isCellEditable et setValueAt du TableModel. Je ne connais pas Hibernate, donc je ne sais pas répondre à l'autre question.
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
29 nov. 2008 à 14:41
oh merci pose sur vos repondes. jai fais deja ces methodes la mais je cherche a rendre my jtable dynamique de façon que je peux modifier les cases et les ligne et les colonnes ??
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
3 déc. 2008 à 23:38
salut,
alors ces truc la il ya changement sur la jtable mais pas sur la base ??
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
4 déc. 2008 à 23:23
slt,
Dans mytableModel jai utiliser tous ces trucs la mais je cherches de faire un uptada a partir de jtable ke je v modifier une case d'elle
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
7 déc. 2008 à 22:43
alors j'ai fait un jComboBox pour le choix de critaire mais je trouve pas comment afficher les donées dans un tableau dasn action performed voila le code:

public class ChoixTable extends Panel {

    private static final long serialVersionUID = 1L;
    private JLabel Choix = null;
    private JLabel Valeur = null;
    private JComboBox jChoix = null;
    private JTextField jText = null;
    private JButton Ok = null;
    private JTable jTable = null;

    /**
     * This is the default constructor
     */
    public ChoixTable() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        GridBagConstraints gridBagConstraints5 =new GridBagConstraints() ;
        gridBagConstraints5.fill = GridBagConstraints.BOTH;
        gridBagConstraints5.gridwidth = 2;
        gridBagConstraints5.gridx = 0;
        gridBagConstraints5.gridy = 0;
        gridBagConstraints5.ipadx = 24;
        gridBagConstraints5.ipady = 25;
        gridBagConstraints5.weightx = 1.0;
        gridBagConstraints5.weighty = 1.0;
        gridBagConstraints5.insets = new Insets(22, 7, 12, 13);
        GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
        gridBagConstraints4.insets = new Insets(4, 14, 21, 160);
        gridBagConstraints4.gridy = 3;
        gridBagConstraints4.ipadx = 60;
        gridBagConstraints4.ipady = 6;
        gridBagConstraints4.gridx = 1;
        GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
        gridBagConstraints3.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints3.gridx = 1;
        gridBagConstraints3.gridy = 2;
        gridBagConstraints3.ipadx = 119;
        gridBagConstraints3.weightx = 1.0;
        gridBagConstraints3.insets = new Insets(7, 90, 7, 72);
        GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
        gridBagConstraints2.fill = GridBagConstraints.VERTICAL;
        gridBagConstraints2.gridx = 1;
        gridBagConstraints2.gridy = 1;
        gridBagConstraints2.ipadx = 125;
        gridBagConstraints2.weightx = 1.0;
        gridBagConstraints2.insets = new Insets(12, 75, 5, 54);
        GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
        gridBagConstraints1.insets = new Insets(5, 43, 4, 16);
        gridBagConstraints1.gridy = 2;
        gridBagConstraints1.ipadx = 17;
        gridBagConstraints1.ipady = 9;
        gridBagConstraints1.gridx = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(12, 45, 5, 13);
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 32;
        gridBagConstraints.ipady = 9;
        gridBagConstraints.gridx = 0;
        Valeur = new JLabel();
        Valeur.setText("      Valeur:");
        Choix = new JLabel();
        Choix.setText("    Choix");
        this.setSize(419, 272);
        this.setLayout(new GridBagLayout());
        this.setBackground(Color.lightGray);
        this.add(Choix, gridBagConstraints);
        this.add(Valeur, gridBagConstraints1);
        this.add(getJChoix(), gridBagConstraints2);
        this.add(getJText(), gridBagConstraints3);
        this.add(getOk(), gridBagConstraints4);
        this.add(getJTable(), gridBagConstraints5);
    }

    /**
     * This method initializes jChoix   
     *    
     * @return javax.swing.JComboBox   
     */
    private JComboBox getJChoix() {
        if (jChoix == null) {
            jChoix = new JComboBox();
            jChoix.addItem("id");
            jChoix.addItem("Non");
            jChoix.addItem("Adresse");
            jChoix.addItem("Ville");
            jChoix.addItem("Code");
            jChoix.addItem("Modedepaiement");
           
        }
        return jChoix;
    }

    /**
     * This method initializes jText   
     *    
     * @return javax.swing.JTextField   
     */
    private JTextField getJText() {
        if (jText == null) {
            jText = new JTextField();
        }
        return jText;
    }

    /**
     * This method initializes Ok   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getOk() {
        if (Ok == null) {
            Ok = new JButton();
            Ok.setText("OK");
            Ok.addActionListener(new java.awt.event.ActionListener()
            {
                public void actionPerformed(java.awt.event.ActionEvent e)
                {
                    System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
                    String choix = (String)jChoix.getSelectedItem();
                   
                    if((choix.equals("id"))||(choix.equals("Code")))
                       
                    {
                        int val=Integer.parseInt(jText.getText());
                   
                    Session session = HibernatUtil.currentSession();                            
                    Criteria criteria = session.createCriteria(Client.class)
                    .add(Restrictions.eq( choix, val));
                    List<Client> Clients = criteria.list();
                       
                   
                    }
:///// ici le crtaire c'est le nom ou ville ou adresse ou mode de paiment enfin jai un affichage de liste mais je peux la sortir dans un tableau /////
                    else
                {
                   
                String val=new String(jText.getText());
               
                Session session = HibernatUtil.currentSession();                            
                Criteria criteria = session.createCriteria(Client.class)
                .add(Restrictions.eq( choix, val));
                List<Client> C = criteria.list();
               
                 for(Iterator it =C.iterator();it.hasNext();)
                     
                 {
                    Client c = (Client) it.next();
                     System.out.println(c.getNom()+"--"
                               +c.getAdresse()+"--"
                            +c.getVille()+"--"
                            +c.getCode()+"--"
                            +c.getModedepaiement());
                            
                    }
                   
                    }
                }

               
                    // TODO Auto-generated method stub
                   
               
            });
        }
        return Ok;
    }

    protected List Clients() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * This method initializes jTable   
     *    
     * @return javax.swing.JTable   
     */
   
    private JTable getJTable() {
        if (jTable == null) {
            jTable = new JTable();           
        }
        return jTable;
    }

d'abitude je fais:
   jTable = new JTable(new MytableModel(Clients()));comme sa jaurais affichage mais cette fois celle ci il na pas accepter la liste clients qui est la sortie de criteria comme vous voyer dans laction performed ??,
il fo ke je fasse koi ???,,
 
0
voilemiss Messages postés 46 Date d'inscription mardi 5 juin 2007 Statut Membre Dernière intervention 16 janvier 2010 4
13 déc. 2008 à 21:10
  slt,


alors jai fais une classe SimpleTableDemo  qui implement  TableModelListener et jai fais des modification ds MyTableModel les voila


public void setValueAt(Object o, int ligne, int colonne)
                {
                    System.out.println("......SetValueAT......");
                    data[ligne][colonne]=o;
                    System.out.println("data['"+ligne+"']['"+colonne+"']= "+o.toString());

                    fireTableCellUpdated(ligne, colonne);   
                    fireTableRowsInserted(getRowCount(), getRowCount());
                    fireTableDataChanged();
                   
                   
               
                }







et voila dans SimpleTableDemo


 public void tableChanged(TableModelEvent e) {
         System.out.println("tableChanged");
          int row = e.getFirstRow();
         int column = e.getColumn();
       MyTableModel  model = (MyTableModel)e.getSource();
      // if (e.getType()==3)
          String columnName = model.getColumnName(column);
          Object data = model.getValueAt( row, column );
            if (e.getType()==TableModelEvent.UPDATE)
           traiterData(data);        
        
           
           
     }







Le prob se pose c'est ou dessus de evenement de jButton ,lupdate se fait dans Jtable mais pas dans la base de données .


    public void actionPerformed(java.awt.event.ActionEvent e) {
                    System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
                    if (tableau.isCellSelected(2, 1))
                        System.out.println("selected");
                    else
                    tableau.setValueAt("ddddddddd", 3, 3);
0
Rejoignez-nous