How to update the rows of a DefaultTableModel in a JTable?

java, jframe, jtable, swing

Solution

Several issues here:

It looks like you need to update the entire table whenever that button is pressed. You have three options here: update the DefaultTableModel using `setDataVector`, recreate a new model from scratch and set it on the JTable with `setModel`, implement your own `TableModel` based on `AbstractTableModel` and firing appropriate TableModel events. You could also update the model using `addRow` and `removeRow`, but that would be very uneffective as it would trigger many events.

To listen for "button pressed" events, rather user an `ActionListener` (and add it using `addActionListener`) or an Action (and set it with `setAction`).

In DefaultTableModel, when you modify the structure, it is not needed to manuall call `fireTableDataChanged();`. It automatically fires appropriate TableModel events whenever you modify the underlying data. Don't call `frame.repaint()` either, it is useless and can be time consuming.

Unrelated: Consider following Java coding conventions (Class name starts with a capital letter) and meaningful variable names.

Problem

Ok I have this table added to a JPanel added to a JFrame. In the mousePressed Event there it instates a new class tData and calls a method which returns data from the database as a string contained in a vector element. What I want to happen, every time the btn is pressed it updates the table, What does happen, every time the btn is pressed it updates the table but adds the same data to the end of the table? What would cause this to happen? ``` Object columnHeaders[] = {"Fname", "Mname", "Lname", "Age"}; Object data[][] = {{}}; final DefaultTableModel dtm = new DefaultTableModel(data, columnHeaders); JTable tb = new JTable(dtm); JScrollPane scrollPane = new JScrollPane(tb); tableWrap.add(scrollPane); btn.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { tData h = new tData(10)); Vector<String> v = h.getInfo(); for(int i = 0; i < v.size() ; i++) { dtm.insertRow(i, new Object[]{v.get(i).split(",")[0], v.get(i).split(",")[1], v.get(i).split(",")[2], v.get(i).split(",")[3]}); } dtm.fireTableDataChanged(); frame.repaint(); } }); ```

Original source