尝试用RowSorter过滤JTable时出现空指针异常



我试图通过使用RowSorter的文本字段中的内容过滤JTable1。当我在字段中输入文本时,我收到这个错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javaapplication2.NewJFrame.newFilter(NewJFrame.java:221)
    at javaapplication2.NewJFrame.access$000(NewJFrame.java:28)
    at javaapplication2.NewJFrame$1.insertUpdate(NewJFrame.java:88)

不确定为什么我得到一个NullPointerException。

下面是我的代码:

package javaapplication2;
import java.util.Vector;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.PropertyStateEvent;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class NewJFrame extends javax.swing.JFrame {
    private Vector<Vector<String>> data; //used for data from database
    private Vector<String> header; //used to store data header
    private Vector<Vector<String>> data2; //used for data from database
    private Vector<String> header2; //used to store data header
    public NewJFrame() throws Exception {
        DbWork newDatabase = new DbWork();
        //get data from database
        data = newDatabase.getEmployee();
         //create header for employee table
        header = new Vector<String>();
        header.add("EmployeeID"); 
        header.add("FirstName"); 
        header.add("LastName"); 
        header.add("MI");
        header.add("HomeAddress");
        header.add("State");
        header.add("Zip");
        header.add("DateOfBirth");
        header.add("HireDate");
        header.add("TerminationDate");
        header.add("LicenseDate");
        header.add("Active");
        header.add("ManagerID");
        header.add("ModifiedID"); 

        data2 = newDatabase.getTrucks();
        //create header for truck table
        header2 = new Vector<String>();
        header2.add("TruckID"); 
        header2.add("VinNumber"); 
        header2.add("Make"); 
        header2.add("Model");
        header2.add("TruckYear");
        header2.add("PriceAcquired");
        header2.add("LicenseNumber");
        header2.add("ModifiedID");
        header2.add("DriverFirstName");
        header2.add("DriverLastName");
        header2.add("DriverMI");

        initComponents();

       new TableRowSorter<TableModel>(model1);
       jTable1.setRowSorter(sorter); 

       txtFilter.getDocument().addDocumentListener( 
            new DocumentListener(){ 
                public void changedUpdate(DocumentEvent e){ 
                    newFilter(); 
                } 
                public void insertUpdate(DocumentEvent e){ 
                    newFilter(); 
                } 
                public void removeUpdate(DocumentEvent e){ 
                    newFilter(); 
                } 
            } 
        );        

    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable(model1);
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        txtFilter = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Tracking System - Prototype");
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            data, header
        ));
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);
        jTabbedPane1.addTab("Employees", jScrollPane1);
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            data2, header2
        ));
        jTable2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jTable2);
        jTabbedPane1.addTab("Trucks", jScrollPane2);
        jButton1.setText("Modify Record");
        jButton2.setText("New Record");
        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);
        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);
        setJMenuBar(jMenuBar1);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addGap(307, 307, 307))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTabbedPane1)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(104, 104, 104)
                        .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 351, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(62, 62, 62))
        );
        pack();
    }// </editor-fold>
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try
                {
                    new NewJFrame().setVisible(true);
                }catch(Exception e){e.printStackTrace();}
            }
        });
    }

    private void newFilter() {
    RowFilter<TableModel, Object> rf = null;
    //If current expression doesn't parse, don't update.
    try {
        rf = RowFilter.regexFilter(txtFilter.getText(),0);
    } catch (Exception e) {
        return;
    }
    sorter.setRowFilter(rf);
}


   TableModel model1 = new DefaultTableModel();
   TableRowSorter<TableModel>sorter;

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField txtFilter;
    // End of variables declaration
}

问题是分类器是…null:-)这是因为您从未设置字段:

// creates a sorter which is nowhere used
new TableRowSorter<TableModel>(model1);
// declares a field that's not initialized
TableRowSorter<TableModel> sorter;
// you have to combine both to initialize the sorter field
sorter = new TableRowSorter<TableModel>(model1);
jTable1.setRowSorter(sorter); 

无论如何,没有必要手动安装rowSorter,让表为您管理它,并在需要时抓取自动创建的排序器:

// configure the table to create a rowSorter as needed
jTable1.setAutoCreateRowSorter(true);
// access the auto-created sorter in newFilter
TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
sorter.setRowFilter(rf); 

相关内容

  • 没有找到相关文章

最新更新