java - 更新数据时刷新 JTable

标签 java swing jtable

下面是我的代码:-

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                     
}

每当我更新表中的数据时,更新的数据都不会反射(reflect)。仅当我重新打开窗口时,才会反射(reflect)更新的数据。 请帮助我度过难关。 提前致谢。

最佳答案

  1. 为什么 DefaultTableModelJTableHeader 的 void 是静态的

  2. DefaultTableModel 中删除行

  3. RowFilter 使用 DocumentListener 而不是 KeyListener

  4. 为什么初始化了两个不同的LookAndFeel

  5. DefaultTableModel 的更新必须在 EDT 上完成,更多信息请参见 Oracle 教程 Concurrency in Swing - The Event Dispatch Thread

  6. 搜索 ResultSetTableModelTableFromDatabaseBeanTableModel

  7. 其余问题隐藏在遮蔽 void 或类中,请注意删除所有静态声明,应该只有静态主类

关于java - 更新数据时刷新 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488643/

相关文章:

Java rowAtPoint() 未返回正确的值

java - 如何在Jtable中的多行中设置焦点?

Java输入编码

Java 程序并不是从头开始,尽管我试图告诉它

java - 我可以使用根相对 XPath 表达式来获取克隆节点中的节点吗?

java - 在另一个类实例中获取一个类实例的变量值

java - Swing:旋转风格化文本?

java - JTable 可水平滚动并增长以填充父容器

java - Android Activity : how to init variable with constructor? 我需要 putExtra 吗?

java - 我可以捕获退出 JTextField 的事件吗