Update Jtable

I have a JTable created from Vector. How to update JTable to display new data added to vector?

+4
source share
2 answers

Your JTable should update automatically when a change occurs in the TableModel. I am doing the jump here, but I assume that you are not using your own TableModel and just call the JTable constructor with your vector. In this case, you can get the binding to the TableModel and pass it to DefaultTableModel, and then call one of the notification methods so that JTable knows about the change, for example:

DefaultTableModel model = (DefaultTableModel)table.getModel(); model.fireTableChanged(new TableModelEvent(........)); 

I would recommend really using your own TableModel if this is not very trivial, but the fact that you are updating the data points to this.

Check out the sun tutorial for working with tables , in particular the section on listening to data changes .

It may seem that more work is ahead, but in the long run it will save you a lot of headaches and be the right way to do it

+16
source

I call the initTable method, followed by loadTable (). I am sure there are many other ways, but it works like acharm.

 private void initBerkheimerTable() { tblBerkheimer = new JTable(); tblBerkheimer.getSelectionModel().addListSelectionListener(new SelectionListener()); tblBerkheimer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblBerkheimer.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "Id", "Name", "Berkheimer PSD", "Rate", "Current PSD", "Current Rate" } ) { Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class, String.class, String.class }; public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } boolean[] columnEditables=new boolean[]{false,false,false,false,false,false,false,false,false,false}; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }); scrollPane.setViewportView(tblBerkheimer); add(scrollPane); } private void loadTable(){ PreparedStatement ps=null; ResultSet rs=null; try { PayrollPsdAuditing.payroll=Database.connectToSQLServerDataBase(PayrollPsdAuditing.payrollIni); ps=PayrollPsdAuditing.payroll.prepareStatement( "SELECT a.EMPLOYID, " + " a.NAME, " + " a.PSD_CODE, " + " a.RATE, " + " b.STRINGS_I_2 as CURRENT_PSD, " + " c.lcltaxrt as CURRENT_RATE " + "FROM PYRL_PSD_VALIDATION a, " + " EX010130 b, " + " UPR41400 c " + "WHERE a.employid=b.empid_i " + " AND c.localtax=b.strings_i_2"); rs=ps.executeQuery(); while(rs.next()) { Swing.fillJTable(tblBerkheimer, new String[]{rs.getString("EMPLOYID").trim() ,rs.getString("NAME").trim() ,rs.getString("PSD_CODE").trim() ,String.valueOf(rs.getDouble("RATE")) ,rs.getString("CURRENT_PSD").trim() ,String.valueOf(rs.getDouble("CURRENT_RATE")/100000)}); } } catch (Exception ex) { ex.printStackTrace(); } finally { Database.close(PayrollPsdAuditing.payroll); } } 
+1
source

All Articles