Thursday, 22 October 2015

Searching In Jtable On Every Key Press

When working with huge data we often need to search specific data in our table in this tutorial we shows how to search data in jtable using textfield  when ever user press key from keyboard it searches the data according to key press rowfilter is used to perform this task.

RowFilter<M,I>:

M: Here we have to specify the name of model we want to add row filter.
I: Type of identifier is specified here.

CODING:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class table extends JFrame{

table()
{
final JTextField t1 = new JTextField(15);
setTitle("Searching In JTable");
JLabel l1 = new JLabel("Search");
setDefaultCloseOperation(EXIT_ON_CLOSE);      
String columnNames[] = {"Product Name","Price"};
Object rowData[][]={{"Light",300},{"Fan",400},{"Bulb",100},{"Egg",50},{"Biscuit",20},{"Milk",80}};
TableModel model = new DefaultTableModel(rowData, columnNames);


final TableRowSorter<TableModel> sorter1 = new TableRowSorter<>(model);

JTable table1 = new JTable(model);
table1.setRowSorter(sorter1);
setLayout(new FlowLayout(FlowLayout.CENTER));
JScrollPane js = new JScrollPane(table1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(l1);
add(t1);
add(js);

t1.getDocument().addDocumentListener(new DocumentListener(){
@Override public void insertUpdate(DocumentEvent e) {
search(t1.getText());

}
@Override public void removeUpdate(DocumentEvent e) {
search(t1.getText());
}
@Override public void changedUpdate(DocumentEvent e) {
search(t1.getText());
}
public void search(String s)
{
if (s.length() == 0) {

sorter1.setRowFilter(null);
} else {

sorter1.setRowFilter(RowFilter.regexFilter(s));
}
}
});
setSize(500,600);
setVisible(true);
}
}

class tab
{
public static void main(String[] args)  {

table x= new table();

}

}

OUTPUT:





No comments:

Post a Comment