Delete button in Jtable

I added a button to every line of my Jtable, but no action. The delete button should remove a row from my Jtable, as well as my database. I was thinking about using a card, the card contains a line number and an identifier in my database, but I am a stack, I could not continue this 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); } } 
0
source share
1 answer

Mark the Column of the table column . It shows how to use JButton as a visualizer and editor for a column. All you have to do is write a custom Action for the editor.

The link gives a simple example of the Delete action, which removes a row from the TableModel . You will need to modify the Action to remove the row from the database.

+1
source

Source: https://habr.com/ru/post/1441057/


All Articles