I use a document listener and it brings me a null pointer exception . How could I stop this exception . I use this for search some content of a table. With using this I could search relevant content . Also this brings me a null pointer exception .
These are the steps,
In the beginning,
Vector originalTableModel;
DocumentListener documentListener;
In the counstructor,
originalTableModel = (Vector) ((DefaultTableModel) list_table.getModel()).getDataVector().clone();
//add document listener to jtextfield to search contents as soon as something typed on it
addDocumentListener();
My documentlistener method,
private void addDocumentListener(){
documentListener = new DocumentListener(){
public void changedUpdate(DocumentEvent documentEvent){
search();
}
public void insertUpdate(DocumentEvent documentEvent){
search();
}
public void removeUpdate(DocumentEvent documentEvent){
search();
}
private void search(){
searchTableContents(search_field.getText());
}
};
}
My searching Method,
public void searchTableContents(String searchString)
{
DefaultTableModel currtableModel = (DefaultTableModel) list_table.getModel();
//To empty the table before search
currtableModel.setRowCount(0);
//To search for contents from original table content
for (Object rows : originalTableModel)
{
Vector rowVector = (Vector) rows;
for (Object column : rowVector)
{
if **(column.toString().toLowerCase().contains(searchString.toLowerCase())**)
{
//content found so adding to table
currtableModel.addRow(rowVector);
break;
}
}
}
}
This is the place where I called this method,
private void search_fieldKeyReleased(java.awt.event.KeyEvent evt)
{
// TODO add your handling code here:
searchTableContents(search_field.getText());
}
I bold the point where I got this null pointer exception.
Have any ideas ?
Most likely your column
variable is null. This will be the case if at least one of the cells in the table is empty. Furthermore, since originalTableModel
is taken as a clone of the table model in the constructor, any changes since the clone was taken till the time searchTableContents
is run will not be reflected in the originalTableModel
.
To fix it, you should change the if to if (column != null && column.toString().toLowerCase().contains(searchString.toLowerCase()))
.