Jtable How to Refresh Table Model After Insert Delete or Update the Data

JTable How to refresh table model after insert delete or update the data.

If you want to notify your JTable about changes of your data, use

tableModel.fireTableDataChanged()

From the documentation:

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

How to refresh a table (JTable) without changing the ordering done with setAutoCreateRowSorter?

I take the new data to be included assigning the array data,

Well you cant do that because that will create a new TableModel which will reset the sorter.

So, assuming you are using the DefaultTableModel, the basic logic should be:

model.setRowCount(0); // to delete the rows

for (each row of data in the Array)
model.addRow(...);

Now only the data will be removed and added to the model so the sorter will remain.

The other option is to save the state of the sorter before recreating the TableModel. You can get the current sort keys from the DefaultRowSorter. So the basic logic would be:

  1. getSortKeys()
  2. refresh TableModel
  3. setSortKeys(...)

See: Trying to get the sorter positon to retain after a table refresh for an example of this approach.

How to refresh JTable after inserting data to database?

Here:

private void loadData() {
...
table = new JTable(model); // don't re-create the table here
}

Don't re-create the table but update its model instead, either by setting a new table model or by clearing and re-filling the current one:

private void loadData() {
...
table.setModel(model);
// Of course, table should have been initialized
// and placed first, and only once!
}

See examples here (includes SwingWorker to make database calls in a background thread), here and here. Please have a look to those answers, there are explanations to make the point clear.

How to refresh data in JTable I am using TableModel

You've done it the hard way.

First of all, you've implemented directly from TableModel and secondly you've failed to implement the listener requirements...

Instead, try extending from the AbstractTableModel instead, which already includes the implementations of the listener registration and notification.

You will need to provide a method that will allow you to add a row to the table model. In this method you need to use the fireTableRowsInserted method which will notify any tables using the model, that a new row has been added...

Update with example

This is VERY, VERY basic example. It's only intention is to demonstrate the use of fireTableRowsInserted. It uses a Swing Timer to add a new row every 125 milliseconds until you kill it ;)

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class DynamicTable {

public static void main(String[] args) {
new DynamicTable();
}

public DynamicTable() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

final MyTableModel model = new MyTableModel();
JTable table = new JTable(model);

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Timer timer = new Timer(125, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.addRow();
}
});
timer.start();
}
});
}

public class MyTableModel extends AbstractTableModel {

private List<String[]> rows;

public MyTableModel() {
rows = new ArrayList<>(25);
}

@Override
public int getRowCount() {
return rows.size();
}

@Override
public int getColumnCount() {
return 4;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
String[] row = rows.get(rowIndex);
return row[columnIndex];
}

public void addRow() {
int rowCount = getRowCount();
String[] row = new String[getColumnCount()];
for (int index = 0; index < getColumnCount(); index++) {
row[index] = rowCount + "x" + index;
}
rows.add(row);
fireTableRowsInserted(rowCount, rowCount);
}
}
}

Updated with another example

Because your table model is backed by its own List, it has no connection to your factory. It doesn't know when you add or remove objects from it. This means you become responsible for updating the model:

public class MyTableModel extends AbstractTableModel {

private List<Staff> staffs;

public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}

@Override
public int getRowCount() {
return staffs.size();
}

@Override
public int getColumnCount() {
return 5;
}

public void add(Staff staff) {
int size = getSize();
staffs.add(staff);
fireTableRowsInserted(size, size);
}

public void remove(Staff staff) {
if (staffs.contains(staff) {
int index = stafff.indexOf(staff);
staffs.remove(staff);
fireTableRowsDeleted(index, index);
}
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
}

And your actionPerformed:

@Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
((MyTableModel)model).add(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
}

Refresh jtable after Delete An item from database

The way you're attempting to remove data seems vary inefficient and just incorrect. It looks like what you are trying to do with your code is create a whole other table and replacing it with a new one. Don't do that. Just update the TableModel. You can just use its method

  • public void removeRow(int row) - Removes the row at row from the model. Notification of the row being removed will be sent to all the listeners.

Just using this method, will automatically remove a row from the table. So you can just do something like this, somewhere in a listener

DefaultTableModel model = (DefaultTableModel)bookTable.getModel();
int row = ...
model.removeRow(row);

All you code where you have **Refresh code** looks simply unnecessary.

Look at DefualtTableModel for more methods, like adding rows and such.

Update JTable after delete or insert

I did not use a direct row index because that may change if the user sorted the data by any one of the columns. I felt that since employeeID was unique that it would be better to match on that:

//remove row in the ResultSet public void removeRow(String empID) {  int rsRow = 0;  try  {   //set cursor to beginning of data set (before first row)   if(!resultSet.isBeforeFirst())    resultSet.beforeFirst();      //iterate through resultSet to find matching record with   //correct employee ID. once found delete row   while(resultSet.next())   {    if(resultSet.getString("EmployeeNo") == empID)    {     rsRow = resultSet.getRow();          resultSet.deleteRow();     System.out.println("User: " + empID + " was deleted from row: " + rsRow);     break;    }   }      resultSet.last();   numRowCount = resultSet.getRow();      fireTableRowsDeleted(rsRow, rsRow);
// resultSet.absolute(rsRow);// resultSet.deleteRow(); } catch (SQLException e) { e.printStackTrace(); } }

How to refresh a JTable after database operations without frame reload?

The answer depends on what type of TableModel you're using...and at what level the events are occuring.

For example, if you have some kind of background Thread or "update" button and want to reload the content from the database, simple create a new TableModel based on the results from the database and apply it to the current JTable, this will update the view automatically.

If you are performing database operations within your application (adding, updating, removing rows), you can provide some kind of notification back to the TableModel and simply update it's content.

For example DefaultTableModel provides addRow, insertRow, removeRow methods. TableModel also provides setValueAt which allows you to change the value of a given cell.

All these methods provide notification back to the JTable that the model is associated with automatically

update jtable model after filtering

to get the proper value do this whenever you need the row from the table:

model.getSelectedEntry(table.convertRowIndexToModel(table.getSelectedRow()));

Jtable does not refresh after inserting a new data

Hai guys finally i found a solution for that,it will be very use full for the people who seeking this type of question's answer,so i would like to post my code here

just make a method called reset()
inside that

  DefaultTableModel model;
model = (DefaultTableModel) jtable1.getModel();

void reset()
{
for(int i=model.getRowCount()-1; i>=0;i--)
{
model.removeRow(i);
}
}

And call this reset method anywhere you want,it will be work fine with simple codes,good luck



Related Topics



Leave a reply



Submit