Yogi Sachdev
Yogi Sachdev

Reputation: 45

Refresh the JTable on updating the data

Below is my code:-

public class MainScreen extends javax.swing.JFrame {

    private TableRowSorter<TableModel> sorter;

    public MainScreen() {
        initComponents();
        this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());

        sorter = new TableRowSorter<>(tblCustomer.getModel());
        tblCustomer.setRowSorter(sorter);
        List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
        System.out.println("I'm here  "+findAll.size());


        ((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
        tblCustomer.setAutoCreateRowSorter(true);
        tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
        tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);

    }

    public static Vector getDataVector(List<BasicDetailsDTO> listData) {
        Vector dataVector = new Vector();
        for (BasicDetailsDTO instance : listData) {
            Vector row = new Vector();
            row.add(instance.getId());
            row.add(instance.getParticulars());
            row.add(instance.getBookedBy());
            row.add(instance.getContactPerson());
            row.add(instance.getMobileNo());
            row.add(instance.getEmail_id());
            dataVector.add(row);

        }
        return dataVector;

    }

    public static Vector getVectorHeader() {

        Vector header = new Vector();
        header.add("ID");
        header.add("Particulars");
        header.add("BOOKED BY");
        header.add("CONTACT PERSON");
        header.add("MOBILE NO");
        header.add("EMAIL ID");
        return header;

    }

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:

        displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
    }                                      

    private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:

        if (tblCustomer.getSelectedRow() == -1) {
            displayError("Please Select the Record");
            return;
        }

        int option = displayConfirmDialog("Do you Really want to delete Record ?");
        if (option == JOptionPane.YES_OPTION) {
            String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
            BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));

            instance.setDeleted(Boolean.TRUE);
            UtilDAO.getDaoBasicDetails().remove(instance);

            List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
            getDataVector(findAll);

            displayMessage(" Record Deleted ");
        }

    }                                         

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:

        if (tblCustomer.getSelectedRow() == -1) {
            displayError("Please select record.");
            return;
        }
        String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
        BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));

        displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);



    }                                       

    private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {                                         
        // TODO add your handling code here:

        if (evt.getClickCount() == 2) {
            String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
            BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));

            displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
        }
    }                                        

    private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        // TODO add your handling code here:

        displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
    }                                                

    private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        // TODO add your handling code here:

        displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
    }                                                 

    private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {                                      
        // TODO add your handling code here:
        if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
            if (txtSearch.getText().trim().length() > 0) {
                RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
                    @Override
                    public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
                        String search = txtSearch.getText().trim().toLowerCase();
                        //   System.out.println(entry.getStringValue(1));
                        return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
                    }
                };
                sorter.setRowFilter(filter);
                //sorter.setRowFilter(null);
                tblCustomer.setRowSorter(sorter);
                // System.out.println("New Row is " + filter);
            } else {
                sorter.setRowFilter(null);
                tblCustomer.setRowSorter(sorter);
            }
        } else {
            if (tblCustomer.getRowCount() > 0) {
                tblCustomer.requestFocus();
                tblCustomer.setRowSelectionInterval(0, 0);
            } else {
                txtSearch.requestFocus();
            }

        }
    }                                     

    private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        try {
            InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);

            IContext context = report.createContext();
            if (tblCustomer.getSelectedRow() == -1) {
                displayError("Please select record.");
                return;
            }
            String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
            BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
            context.put("Customer", instance);



            OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
            report.process(context, out);
            Desktop desktop = Desktop.getDesktop();
            File f = new File("Passenger Name_Out.docx");
            desktop.open(f);


        } catch (IOException | XDocReportException ex) {
            Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {

                    UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
                }
                new MainScreen().setVisible(true);
            }
        });

    }

    public static void setlblMessageDetail(String msg) {

        MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
        MainScreen.lblMessage.setText(msg);
    }
    // Variables declaration - do not modify                     
}

Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window. Kindly help me through. Thanks in advance.

Upvotes: 0

Views: 190

Answers (1)

mKorbel
mKorbel

Reputation: 109823

  1. why voids for DefaultTableModel and JTableHeader are static

  2. remove rows from DefaultTableModel

  3. use DocumentListener instead of KeyListener for RowFilter

  4. why is there initialized two different LookAndFeels

  5. updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread

  6. search for ResultSetTableModel, TableFromDatabase, BeanTableModel

  7. rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class

Upvotes: 2

Related Questions