Accueil > > > JTABLE GÉNÉRIQUE : TRI,AJOUT,SUPPRESSION,CTRL CLASSE,TAILLE COL,SÉLECTION DES COL,RECUP LIGNES SUPP
JTABLE GÉNÉRIQUE : TRI,AJOUT,SUPPRESSION,CTRL CLASSE,TAILLE COL,SÉLECTION DES COL,RECUP LIGNES SUPP
Information sur la source
Description
Permet d'utliser une jtable de manière générique et dynamique !
Source
- Utilisation de la jtable :
- Déclarer:
- public TableModelPerso T;
- public Tableur TAB;
- Appel:
- T=new TableModelPerso (
- vect, // de type Object[][] contient les données
- Colemploye, //de type String[] contient les entetes de col
- false, // false si maj,true si sélection uniquement
- vcoleditable, //de type Boolean[] les colonnes modifiables = true
- ctrlcolemploye, //de type String[] classes des col int,long,double,float,string,date,boolean
- vsize); // de type int[] taille des colonnes
- TAB=new Tableur(T,1); // 0 si interdiction d'ajouter ou supprimer les lignes,1 sinon
- TAB.affiche(this);
-
- // le retour se fait via l'évents windowActivated de votre frame
- // récupère les données via T.getDonnees() de type Object[][]
- //récupère les lignes supp via T.getLignesup() de type Object[][]
-
- copier ces deux classes
-
- 1
-
- import javax.swing.*;
- import javax.swing.table.TableModel;
- import javax.swing.event.*;
- import java.awt.Dimension;
- import java.awt.event.*;
- import javax.swing.table.DefaultTableColumnModel;
- import javax.swing.table.AbstractTableModel;
- import java.awt.Color;
- import java.awt.*;
- import javax.swing.JButton;
- import javax.swing.table.DefaultTableModel;
-
-
- class Tableur extends JPanel implements TableModelListener
- {
- private Object[][] donnees;
- private String[] nomsColonnes;
- private JTable table;
- private TableModel tableur;
- private int[] vsize;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JButton aj1,aj2;
- private TableModelPerso tt;
- private int ajoutsupp;
- private int posilig;
-
-
-
-
- Tableur(TableModelPerso vtablemodelperso,int vajoutsupp)
- {
- tt=vtablemodelperso;
- ajoutsupp=vajoutsupp;
- this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
- table = new JTable(vtablemodelperso);
- table.setColumnSelectionAllowed(true);
- table.setRowSelectionAllowed(true);
- table.setSelectionBackground(Color.BLUE);
- table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
- int[] vsize=vtablemodelperso.getSizecol();
- int tailletot=0;
- for (int i=0;i<vsize.length;i++)
- {
- table.getColumnModel().getColumn(i).setPreferredWidth(vsize[i]);
- if (vsize[i]==0) {table.getColumnModel().getColumn(i).setMinWidth(vsize[i]);table.getColumnModel().getColumn(i).setMaxWidth(vsize[i]);}
- tailletot=tailletot+vsize[i];
- }
- vtablemodelperso.addEcouteur(table);
- table.setPreferredScrollableViewportSize(new Dimension(tailletot+100, 300));
- JScrollPane avecAsc = new JScrollPane(table);
- jLabel1 = new javax.swing.JLabel();
- jLabel1.setBackground(new java.awt.Color(255, 255, 51));
- jLabel1.setText("Double clic sur une colonne pour trier la table");
- jLabel1.setOpaque(true);
- jLabel1.setName("TITRE");
- jLabel1.setPreferredSize(new java.awt.Dimension(55, 20));
- aj1 = new javax.swing.JButton();
- aj1.setBackground(new java.awt.Color(255, 255, 51));
- aj1.setText("Ajouter une ligne");
- aj1.setPreferredSize(new java.awt.Dimension(150, 25));
- aj2 = new javax.swing.JButton();
- aj2.setBackground(new java.awt.Color(255, 255, 51));
- aj2.setText("Supprimer une ligne");
- aj2.setPreferredSize(new java.awt.Dimension(150, 25));
- add(jLabel1);
- add(avecAsc);
- table.addMouseListener(new java.awt.event.MouseAdapter() {
- public void mouseClicked(java.awt.event.MouseEvent evt) {
- posilig=(table.rowAtPoint(evt.getPoint()));
- }
- });
- if (!vtablemodelperso.isTypeselection() & ajoutsupp!=0){
- add(aj1);
- aj1.addMouseListener(new java.awt.event.MouseAdapter() {
- public void mouseClicked(java.awt.event.MouseEvent evt) {
- tt.addligne();
- }});
- add(aj2);
- aj2.addMouseListener(new java.awt.event.MouseAdapter() {
- public void mouseClicked(java.awt.event.MouseEvent evt) {
- if (tt.getDonnees().length==0)
- {
- JOptionPane d = new JOptionPane();
- d.showMessageDialog( d.getParent(),"Plus de ligne!","Erreur!",JOptionPane.ERROR_MESSAGE);
- return;
- }
- table.changeSelection(posilig,0,false,false);
- for (int k=0;k<tt.getColumnCount();k++)
- {
- table.changeSelection(posilig,k,false,true);
- }
- tt.suppligne(posilig);
- }});
- }
- }
- public void tableChanged(TableModelEvent e)
- {
- }
- public void affiche( JFrame j,String vtitre)
- {
- final JFrame v=j;
- JFrame monCadre = new JFrame();
- monCadre.setTitle(vtitre);
- monCadre.setContentPane(this);
- monCadre.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent evt)
- {
- v.show();
- }
- });
- Insets insets = monCadre.getInsets();
- monCadre.setSize(300 + insets.left + insets.right,125 + insets.top + insets.bottom);
- java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
- monCadre.setBounds((screenSize.width-800)/2, (screenSize.height-600)/2, 800, 600);
- monCadre.pack();
- monCadre.setVisible(true);
- }
-
- public Point getLocation() {
- Point retValue;
- retValue = super.getLocation();
- System.out.println(retValue);
- return retValue;
- }
- public String[] getNomsColonnes() {
- return nomsColonnes;
- }
- }
-
-
- 2
-
- import javax.swing.table.AbstractTableModel;
- import javax.swing.AbstractCellEditor;
- import javax.swing.table.TableCellEditor;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.util.Arrays;
- import java.util.Date;
- import java.text.SimpleDateFormat;
-
- public class TableModelPerso extends AbstractTableModel
- {
- private Object[][] donnees,donnees1,lignesup,lignesup1,copydonnees;
- private String[] nomsColonnes;
- private boolean[] colmodifiable;
- private boolean typeselection;
- private String[] ctrlcol;
- private int[] sizecol;
- private Ligne[] lignes,lignes1;
- private int colonneTri;
- private Boolean vyes=new Boolean (true);
-
-
- private Boolean vno=new Boolean (false);
- private TableModelPerso model;
-
-
- public TableModelPerso (Object[][] vdonnees, String[] vnomsColonnes,boolean vtypeselection,boolean[] vcolmodifiable,String vctrlcol[],int[] vsizecol) {
-
- typeselection=vtypeselection;
- ctrlcol=new String[vctrlcol.length];
- sizecol=new int[vsizecol.length];
- if (typeselection==true){
- donnees=new Object[vdonnees.length][vnomsColonnes.length+1];
- nomsColonnes=new String[vnomsColonnes.length+1];
- nomsColonnes[vnomsColonnes.length]="Sélection";
- colmodifiable=new boolean[vcolmodifiable.length+1];
- colmodifiable[vcolmodifiable.length]=true;
- int i;
- for (i=0;i<donnees.length;i++)
- { donnees[i][vnomsColonnes.length]=vno; }
- donnees[0][vnomsColonnes.length]=vyes;
- }
- else
- {
- lignesup=new Object[vdonnees.length][vnomsColonnes.length];
- donnees=new Object[vdonnees.length][vnomsColonnes.length];
- nomsColonnes=new String[vnomsColonnes.length];
- colmodifiable=new boolean[vcolmodifiable.length];
- }
-
- int i,j;
- for (i=0;i<vdonnees.length;i++)
- {
- for (j=0;j<vnomsColonnes.length;j++)
- {donnees[i][j]=vdonnees[i][j];}
- }
- for (j=0;j<vnomsColonnes.length;j++)
- {
- nomsColonnes[j]=vnomsColonnes[j];
- if (typeselection==true)
- colmodifiable[j]=false;
- else
- colmodifiable[j]=vcolmodifiable[j];
- }
- for (j=0;j<vctrlcol.length;j++)
- {ctrlcol[j]=vctrlcol[j];}
- for (j=0;j<vsizecol.length;j++)
- {sizecol[j]=vsizecol[j];}
- model=this;
- lignes = new Ligne[model.getRowCount()];
- for (i = 0; i < lignes.length; i++) {
- lignes[i] = new Ligne();
- lignes[i].index = i;
- }
- }
-
- public boolean isCellEditable(int row, int col) {
-
- if (colmodifiable[col]==false)
- return false;
- else
- return true;
- }
- public int getColumnCount() {
- return nomsColonnes.length;
- }
- public Object getValueAt(int parm1, int parm2) {
- return donnees[parm1][parm2];
-
- }
- public int getRowCount() {
- return donnees.length;
- }
- public String getColumnName(int col){
- return nomsColonnes[col];
- }
- public Object[][] getDonnees() {
- return donnees;
- }
- public Object[][] getLignesup() {
- return lignesup;
- }
- public void setValueAt(Object value, int row, int col) {
- if (typeselection)
- {
- int i;
- for(i=0;i<donnees.length;i++)
- {
- if ((donnees[i][nomsColonnes.length-1])==vyes)
- donnees[i][nomsColonnes.length-1]=vno;
- }
- donnees[row][nomsColonnes.length-1]=vyes;
- fireTableDataChanged();
- }
- else
- {
- // on peut ajouter d'autres ctrl depend de la façon dont vous gérer les nombres'
- if (ctrlcol[col].equalsIgnoreCase("Date"))
- {
- try {java.sql.Date dd=java.sql.Date.valueOf((String) value);donnees[row][col]=value;fireTableDataChanged();}
- catch (Exception e){
- JOptionPane d = new JOptionPane();
- d.showMessageDialog( d.getParent(),"Erreur de date","Attention !",JOptionPane.ERROR_MESSAGE);
- }
- }
- else
- {
- if (value!=null)
- {
- if (value.getClass() != getColumnClass(col))
- {
- donnees[row][col]=null;
- }
- else
- {
- donnees[row][col]=value;}
- }
-
- fireTableDataChanged();
- }
- }
- }
- public void clear () {
- for (int i = 0;i < nomsColonnes.length;i++)
- donnees[i]=null;
- fireTableDataChanged();
- }
- public Class getColumnClass(int columnIndex) {
- return getValueAt(0, columnIndex).getClass();
- }
- public boolean isTypeselection() {
- return typeselection;
- }
- public int[] getSizecol() {
- return sizecol;
- }
-
- private class Ligne implements Comparable {
- public int index;
- public int compareTo(Object autre) {
- Ligne autreLigne = (Ligne)autre;
- Object cellule = model.getValueAt(index, colonneTri);
- Object autreCellule = model.getValueAt(autreLigne.index, colonneTri);
- return ((Comparable)cellule).compareTo(autreCellule );
- }
- }
- public void addEcouteur(final JTable table) {
- table.getTableHeader().addMouseListener(new MouseAdapter() {
- public void mouseClicked(MouseEvent event) {
- if (event.getClickCount() < 2) return;
- int tableColumn = table.columnAtPoint(event.getPoint());
- int modelColumn = table.convertColumnIndexToModel(tableColumn);
- sort(modelColumn);
- }
- });
- }
- public void sort(int c) {
- colonneTri = c;
- Arrays.sort(lignes);
- copydonnees=new Object [donnees.length][nomsColonnes.length];
- for (int j=0;j<lignes.length;j++){copydonnees[j]=donnees[lignes[j].index];}
- for (int j=0;j<lignes.length;j++){donnees[j]=copydonnees[j];}
- fireTableDataChanged();
- }
- public void addligne() {
- int i;
- donnees1=new Object[donnees.length+1][nomsColonnes.length];
- lignesup1=new Object[lignesup.length+1][nomsColonnes.length];
- for ( i=0;i<donnees.length;i++){donnees1[i]=donnees[i];}
- for (int j=0;j<nomsColonnes.length;j++)
- { // dépend de la façon dont vous gérez les nombres (string ou non)
- if (ctrlcol[j].equalsIgnoreCase("int")) donnees1[i][j]=new Integer(0);
- if (ctrlcol[j].equalsIgnoreCase("long")) donnees1[i][j]=new Long (0);
- if (ctrlcol[j].equalsIgnoreCase("float")) donnees1[i][j]=new Float (0);
- if (ctrlcol[j].equalsIgnoreCase("double")) donnees1[i][j]=new Double (0);
- if (ctrlcol[j].equalsIgnoreCase("string")) donnees1[i][j]="";
- if (ctrlcol[j].equalsIgnoreCase("char")) donnees1[i][j]="";
- if (ctrlcol[j].equalsIgnoreCase("date"))
- {
- Date datejour=new Date();
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- donnees1[i][j]=formatter.format(datejour);
- }
- if (ctrlcol[j].equalsIgnoreCase("boolean")) donnees1[i][j]=vyes;
-
- }
- donnees=donnees1;
- fireTableDataChanged();
- lignes1 = new Ligne[this.getRowCount()];
- for (i = 0; i < lignes1.length; i++)
- {
- lignes1[i] = new Ligne();
- lignes1[i].index = i;
- }
- for(i=0;i<lignesup.length;i++)
- {
- lignesup1[i]=lignesup[i];
- }
- lignesup=lignesup1;
- lignes=lignes1;
- fireTableDataChanged();
- }
- public void suppligne(int lig) {
- JOptionPane d = new JOptionPane();
- int rep=d.showConfirmDialog( d.getParent(),"Supprimer une ligne","Voulez vous reelement supprimer cette ligne ?",JOptionPane.OK_CANCEL_OPTION );
- if (rep!=0) return;
-
- int i;
- donnees1=new Object[donnees.length-1][nomsColonnes.length];
- int j,h;j=0;h=0;
- while (lignesup[h][0]!=null)
- {h=h+1;}
- lignesup[h]=donnees[lig];
- for ( i=0;i<donnees.length;i++)
- {
- if (i!=lig) {donnees1[j]=donnees[i];j=j+1;}
- }
- donnees=donnees1;
- fireTableDataChanged();
- lignes1 = new Ligne[this.getRowCount()];
- for (i = 0; i < lignes1.length; i++)
- {
- lignes1[i] = new Ligne();
- lignes1[i].index = i;
- }
- lignes=lignes1;
- fireTableDataChanged();
- }
- public String[] getNomsColonnes() {
- return nomsColonnes;
- }
- }
-
Utilisation de la jtable :
Déclarer:
public TableModelPerso T;
public Tableur TAB;
Appel:
T=new TableModelPerso (
vect, // de type Object[][] contient les données
Colemploye, //de type String[] contient les entetes de col
false, // false si maj,true si sélection uniquement
vcoleditable, //de type Boolean[] les colonnes modifiables = true
ctrlcolemploye, //de type String[] classes des col int,long,double,float,string,date,boolean
vsize); // de type int[] taille des colonnes
TAB=new Tableur(T,1); // 0 si interdiction d'ajouter ou supprimer les lignes,1 sinon
TAB.affiche(this);
// le retour se fait via l'évents windowActivated de votre frame
// récupère les données via T.getDonnees() de type Object[][]
//récupère les lignes supp via T.getLignesup() de type Object[][]
copier ces deux classes
1
import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.event.*;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.AbstractTableModel;
import java.awt.Color;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;
class Tableur extends JPanel implements TableModelListener
{
private Object[][] donnees;
private String[] nomsColonnes;
private JTable table;
private TableModel tableur;
private int[] vsize;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton aj1,aj2;
private TableModelPerso tt;
private int ajoutsupp;
private int posilig;
Tableur(TableModelPerso vtablemodelperso,int vajoutsupp)
{
tt=vtablemodelperso;
ajoutsupp=vajoutsupp;
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
table = new JTable(vtablemodelperso);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
table.setSelectionBackground(Color.BLUE);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int[] vsize=vtablemodelperso.getSizecol();
int tailletot=0;
for (int i=0;i<vsize.length;i++)
{
table.getColumnModel().getColumn(i).setPreferredWidth(vsize[i]);
if (vsize[i]==0) {table.getColumnModel().getColumn(i).setMinWidth(vsize[i]);table.getColumnModel().getColumn(i).setMaxWidth(vsize[i]);}
tailletot=tailletot+vsize[i];
}
vtablemodelperso.addEcouteur(table);
table.setPreferredScrollableViewportSize(new Dimension(tailletot+100, 300));
JScrollPane avecAsc = new JScrollPane(table);
jLabel1 = new javax.swing.JLabel();
jLabel1.setBackground(new java.awt.Color(255, 255, 51));
jLabel1.setText("Double clic sur une colonne pour trier la table");
jLabel1.setOpaque(true);
jLabel1.setName("TITRE");
jLabel1.setPreferredSize(new java.awt.Dimension(55, 20));
aj1 = new javax.swing.JButton();
aj1.setBackground(new java.awt.Color(255, 255, 51));
aj1.setText("Ajouter une ligne");
aj1.setPreferredSize(new java.awt.Dimension(150, 25));
aj2 = new javax.swing.JButton();
aj2.setBackground(new java.awt.Color(255, 255, 51));
aj2.setText("Supprimer une ligne");
aj2.setPreferredSize(new java.awt.Dimension(150, 25));
add(jLabel1);
add(avecAsc);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
posilig=(table.rowAtPoint(evt.getPoint()));
}
});
if (!vtablemodelperso.isTypeselection() & ajoutsupp!=0){
add(aj1);
aj1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tt.addligne();
}});
add(aj2);
aj2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
if (tt.getDonnees().length==0)
{
JOptionPane d = new JOptionPane();
d.showMessageDialog( d.getParent(),"Plus de ligne!","Erreur!",JOptionPane.ERROR_MESSAGE);
return;
}
table.changeSelection(posilig,0,false,false);
for (int k=0;k<tt.getColumnCount();k++)
{
table.changeSelection(posilig,k,false,true);
}
tt.suppligne(posilig);
}});
}
}
public void tableChanged(TableModelEvent e)
{
}
public void affiche( JFrame j,String vtitre)
{
final JFrame v=j;
JFrame monCadre = new JFrame();
monCadre.setTitle(vtitre);
monCadre.setContentPane(this);
monCadre.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
v.show();
}
});
Insets insets = monCadre.getInsets();
monCadre.setSize(300 + insets.left + insets.right,125 + insets.top + insets.bottom);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
monCadre.setBounds((screenSize.width-800)/2, (screenSize.height-600)/2, 800, 600);
monCadre.pack();
monCadre.setVisible(true);
}
public Point getLocation() {
Point retValue;
retValue = super.getLocation();
System.out.println(retValue);
return retValue;
}
public String[] getNomsColonnes() {
return nomsColonnes;
}
}
2
import javax.swing.table.AbstractTableModel;
import javax.swing.AbstractCellEditor;
import javax.swing.table.TableCellEditor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.Date;
import java.text.SimpleDateFormat;
public class TableModelPerso extends AbstractTableModel
{
private Object[][] donnees,donnees1,lignesup,lignesup1,copydonnees;
private String[] nomsColonnes;
private boolean[] colmodifiable;
private boolean typeselection;
private String[] ctrlcol;
private int[] sizecol;
private Ligne[] lignes,lignes1;
private int colonneTri;
private Boolean vyes=new Boolean (true);
private Boolean vno=new Boolean (false);
private TableModelPerso model;
public TableModelPerso (Object[][] vdonnees, String[] vnomsColonnes,boolean vtypeselection,boolean[] vcolmodifiable,String vctrlcol[],int[] vsizecol) {
typeselection=vtypeselection;
ctrlcol=new String[vctrlcol.length];
sizecol=new int[vsizecol.length];
if (typeselection==true){
donnees=new Object[vdonnees.length][vnomsColonnes.length+1];
nomsColonnes=new String[vnomsColonnes.length+1];
nomsColonnes[vnomsColonnes.length]="Sélection";
colmodifiable=new boolean[vcolmodifiable.length+1];
colmodifiable[vcolmodifiable.length]=true;
int i;
for (i=0;i<donnees.length;i++)
{ donnees[i][vnomsColonnes.length]=vno; }
donnees[0][vnomsColonnes.length]=vyes;
}
else
{
lignesup=new Object[vdonnees.length][vnomsColonnes.length];
donnees=new Object[vdonnees.length][vnomsColonnes.length];
nomsColonnes=new String[vnomsColonnes.length];
colmodifiable=new boolean[vcolmodifiable.length];
}
int i,j;
for (i=0;i<vdonnees.length;i++)
{
for (j=0;j<vnomsColonnes.length;j++)
{donnees[i][j]=vdonnees[i][j];}
}
for (j=0;j<vnomsColonnes.length;j++)
{
nomsColonnes[j]=vnomsColonnes[j];
if (typeselection==true)
colmodifiable[j]=false;
else
colmodifiable[j]=vcolmodifiable[j];
}
for (j=0;j<vctrlcol.length;j++)
{ctrlcol[j]=vctrlcol[j];}
for (j=0;j<vsizecol.length;j++)
{sizecol[j]=vsizecol[j];}
model=this;
lignes = new Ligne[model.getRowCount()];
for (i = 0; i < lignes.length; i++) {
lignes[i] = new Ligne();
lignes[i].index = i;
}
}
public boolean isCellEditable(int row, int col) {
if (colmodifiable[col]==false)
return false;
else
return true;
}
public int getColumnCount() {
return nomsColonnes.length;
}
public Object getValueAt(int parm1, int parm2) {
return donnees[parm1][parm2];
}
public int getRowCount() {
return donnees.length;
}
public String getColumnName(int col){
return nomsColonnes[col];
}
public Object[][] getDonnees() {
return donnees;
}
public Object[][] getLignesup() {
return lignesup;
}
public void setValueAt(Object value, int row, int col) {
if (typeselection)
{
int i;
for(i=0;i<donnees.length;i++)
{
if ((donnees[i][nomsColonnes.length-1])==vyes)
donnees[i][nomsColonnes.length-1]=vno;
}
donnees[row][nomsColonnes.length-1]=vyes;
fireTableDataChanged();
}
else
{
// on peut ajouter d'autres ctrl depend de la façon dont vous gérer les nombres'
if (ctrlcol[col].equalsIgnoreCase("Date"))
{
try {java.sql.Date dd=java.sql.Date.valueOf((String) value);donnees[row][col]=value;fireTableDataChanged();}
catch (Exception e){
JOptionPane d = new JOptionPane();
d.showMessageDialog( d.getParent(),"Erreur de date","Attention !",JOptionPane.ERROR_MESSAGE);
}
}
else
{
if (value!=null)
{
if (value.getClass() != getColumnClass(col))
{
donnees[row][col]=null;
}
else
{
donnees[row][col]=value;}
}
fireTableDataChanged();
}
}
}
public void clear () {
for (int i = 0;i < nomsColonnes.length;i++)
donnees[i]=null;
fireTableDataChanged();
}
public Class getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
public boolean isTypeselection() {
return typeselection;
}
public int[] getSizecol() {
return sizecol;
}
private class Ligne implements Comparable {
public int index;
public int compareTo(Object autre) {
Ligne autreLigne = (Ligne)autre;
Object cellule = model.getValueAt(index, colonneTri);
Object autreCellule = model.getValueAt(autreLigne.index, colonneTri);
return ((Comparable)cellule).compareTo(autreCellule );
}
}
public void addEcouteur(final JTable table) {
table.getTableHeader().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
if (event.getClickCount() < 2) return;
int tableColumn = table.columnAtPoint(event.getPoint());
int modelColumn = table.convertColumnIndexToModel(tableColumn);
sort(modelColumn);
}
});
}
public void sort(int c) {
colonneTri = c;
Arrays.sort(lignes);
copydonnees=new Object [donnees.length][nomsColonnes.length];
for (int j=0;j<lignes.length;j++){copydonnees[j]=donnees[lignes[j].index];}
for (int j=0;j<lignes.length;j++){donnees[j]=copydonnees[j];}
fireTableDataChanged();
}
public void addligne() {
int i;
donnees1=new Object[donnees.length+1][nomsColonnes.length];
lignesup1=new Object[lignesup.length+1][nomsColonnes.length];
for ( i=0;i<donnees.length;i++){donnees1[i]=donnees[i];}
for (int j=0;j<nomsColonnes.length;j++)
{ // dépend de la façon dont vous gérez les nombres (string ou non)
if (ctrlcol[j].equalsIgnoreCase("int")) donnees1[i][j]=new Integer(0);
if (ctrlcol[j].equalsIgnoreCase("long")) donnees1[i][j]=new Long (0);
if (ctrlcol[j].equalsIgnoreCase("float")) donnees1[i][j]=new Float (0);
if (ctrlcol[j].equalsIgnoreCase("double")) donnees1[i][j]=new Double (0);
if (ctrlcol[j].equalsIgnoreCase("string")) donnees1[i][j]="";
if (ctrlcol[j].equalsIgnoreCase("char")) donnees1[i][j]="";
if (ctrlcol[j].equalsIgnoreCase("date"))
{
Date datejour=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
donnees1[i][j]=formatter.format(datejour);
}
if (ctrlcol[j].equalsIgnoreCase("boolean")) donnees1[i][j]=vyes;
}
donnees=donnees1;
fireTableDataChanged();
lignes1 = new Ligne[this.getRowCount()];
for (i = 0; i < lignes1.length; i++)
{
lignes1[i] = new Ligne();
lignes1[i].index = i;
}
for(i=0;i<lignesup.length;i++)
{
lignesup1[i]=lignesup[i];
}
lignesup=lignesup1;
lignes=lignes1;
fireTableDataChanged();
}
public void suppligne(int lig) {
JOptionPane d = new JOptionPane();
int rep=d.showConfirmDialog( d.getParent(),"Supprimer une ligne","Voulez vous reelement supprimer cette ligne ?",JOptionPane.OK_CANCEL_OPTION );
if (rep!=0) return;
int i;
donnees1=new Object[donnees.length-1][nomsColonnes.length];
int j,h;j=0;h=0;
while (lignesup[h][0]!=null)
{h=h+1;}
lignesup[h]=donnees[lig];
for ( i=0;i<donnees.length;i++)
{
if (i!=lig) {donnees1[j]=donnees[i];j=j+1;}
}
donnees=donnees1;
fireTableDataChanged();
lignes1 = new Ligne[this.getRowCount()];
for (i = 0; i < lignes1.length; i++)
{
lignes1[i] = new Ligne();
lignes1[i].index = i;
}
lignes=lignes1;
fireTableDataChanged();
}
public String[] getNomsColonnes() {
return nomsColonnes;
}
}
Conclusion
Merci pour vos commentaires, remerciements aux autres codes sur les jtables
Historique
- 29 janvier 2007 15:43:44 :
- correction des variables à déclarer prog princip
- 29 janvier 2007 16:01:22 :
- mots clés
- 29 janvier 2007 23:01:14 :
- amélioration
- 29 janvier 2007 23:52:59 :
- Amélioration sizecol à zéro
- 05 février 2007 19:31:34 :
- Récupération des lignes supp, possibilité d'interdire l'ajout ou la suppression de lignes
- 05 février 2007 19:33:36 :
- Amélioration
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
une JTable sous java [ par strikers ]
j'ai relier une base de donner a ma JTable et j'ai une colonne Password dans ma Jtable et je s'est pas comment on fais pour qu'il mette des estérixe d
gestion commerciale [ par omar2fatnassi ]
theme de la gestion est :1- ajout d'un client2- suppression d'un client 3- mise a jour 4- recherche d'un client5- gesion des commandes aux pres des fo
Problèmes avec des JTable [ par zarbydigital ]
Hello.Je suis en train de developper une applic' avec une JTable et j'aimerai lui mettre un scroller.Je cré une JTable (JTable jTableNom = new JTalbe)
bouton delete dans une cellule d'unen JTable [ par empiret ]
Bonjour, J'ai une JTable qui contient des lignes. Chaque ligne contient une cellule contenant un bouton 'delete'. Ce bouton sert a supprimer la ligne
comment compiler une classe java pour acceder au tri des modificateur,methodes,proprietées.. [ par red_star16 ]
J'ai essayé de realiser ça mais je n'ai pas assez d'information sur la compilation des classe.si vous pouvez m'aider je serais trè
Inserer une image dans une case de JTable [ par adakick ]
Bonjour, je voulais savoir comment je pourrai mettre une image dans une case de JTable, j'ai essaier sa: for(int i = 0 ; i< data.length
Jtable et erreur ! [ par jimmy69 ]
Bonjour a tous,J'ai un p'tit souci avec mon application qui ne fait que d'ajouter des composant sur un JFrame !lorsque j'ajoute un jtable et que
Les Jtable en Java [ par BookerT ]
Je veux creer un Jtable sur netbeans, pour afficher ma bd... j'arrive pas a changer les nombre de colonnes et de lignes de mon Jtable.... si qq1 sait
comment faire le tri d'un tableau en java [ par belkhouribchiamajda ]
<TD id=HB_Focus_Element vAlign=top width="100%" background="" height=250 UNSELECTAB
Comment ajouter des boutons de suppression a chaque ligne d'une JTable? [ par tomkc ]
Salut,Je recherche le moyen d'ajouter un bouton d'edition et un bouton de suppression à la fin de chaque ligne d'une JTable. Si quelqu'un po
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|