Reputation: 21
I added a button in each row of my Jtable, but without action. The button "delete" must delete the row from my Jtable and also my database. I thought of using map, the map contains the row number and id in my database, but i'm stack, i couldn't continue with that logic.
here is my code :
public class Fenetre extends JFrame {
Statement stmt;
Map<Integer,Integer> row_table = new HashMap<Integer,Integer>();
public Fenetre(){
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTable");
this.setSize(600, 140);
String requeteListeUser=" SELECT * FROM COMPTE_UTILISATEUR";
try{
stmt= (Statement) new Connexion().getConnection().createStatement();
ResultSet resultat= stmt.executeQuery(requeteListeUser);
resultat.last();
String title[] = {"Nom","Prenom","Matricule","Action"};
int rowCount = resultat.getRow();
Object[][] data = new Object[rowCount][4];
JTable tableau = new JTable(data,title);
// this.tableau = new JTable(model);
tableau.getColumn("Action").setCellRenderer(new ButtonRenderer());
this.getContentPane().add(new JScrollPane(tableau), BorderLayout.CENTER);
int i=0;
resultat.beforeFirst(); // on repositionne le curseur avant la première ligne
while(resultat.next()) //tant qu'on a quelque chose à lire
{
//Remplire le tableau à deux dimensions Data[][]
for(int j=1;j<=4;j++)
{
if(j != 4)data[i][j-1]=resultat.getObject(j)+"";
else data[i][j-1] = new JButton("Supprimer");
}
i++;
row_table.put(i, resultat.getInt("id_utilisateur"));
}
}
catch(SQLException ex){
System.out.println(ex);
}
}
//Classe model customized
class ZModel extends AbstractTableModel{
private Object[][] data;
private String[] title;
//Constructor
public ZModel(Object[][] data, String[] title){
this.data = data;
this.title = title;
}
//Number of columns
public int getColumnCount() {
return this.title.length;
}
//Number of rows
public int getRowCount() {
return this.data.length;
}
//The value at the specified à l'emplacement spécifié
public Object getValueAt(int row, int col) {
return this.data[row][col];
}
}
public class ButtonRenderer extends JButton implements TableCellRenderer{
public Component getTableCellRendererComponent(JTable table,Objectvalue,booleanisSelected, boolean isFocus, int row, int col) {
//On écrit dans le bouton ce que contient la cellule
setText("Suuprimer");
//On retourne notre bouton
return this;
} }
public static void main(String[] args){
Fenetre fen = new Fenetre();
fen.setVisible(true);
}
}
Upvotes: 0
Views: 4351
Reputation: 324118
Check out Table Button Column. It shows how to use a JButton as a renderer and editor for a column. All you need to do is write the custom Action
for the editor.
The link gives a simple example of a Delete Action that deletes a row from the TableModel
. You would need to modify the Action
to remove the row from the Database.
Upvotes: 2