Filtering JTable

Assume you have an app that has a JTable displayed on the main frame. There is also a combo box that goes with this JTable for use in filtering the JTable so that only the desired entries are shown in the table.
What is the proper way to handle this filtering?
Do I need to work with the original table model? Or should I create a new table model for each filter action and then find a way to replace the table model that the JTable is using?

I created a tablemodel which accepts an arraylist of objects which are essentially the rows. When I want to filter, I replace that arraylist with a new list (setList() method in tablemodel) which has the filtered records. When a filter is changed, make a new call to the database to get the rows. Or you might want to add a isInSet() method to the row object to simplify building a filtered list from a 'full list'. The outer container (which contains the table and combo) controls which list is displayed.
My code is not very relevant because I built custom SQL statements based on criteria entered in a table and most of the work is done by a custom record cache class I wrote. This means the logic I described above is scattered through several classes.

Similar Messages

  • JTable TAB key listener

    Hi all:
    I'm trying to write a filterable jtable. User can input the filter rule in the table header and the table displays the filtered data at the same time when the user inputs letters. The table filter works fine. But when I try to add "TAB" key listener, I find that I can't track the "TAB" key. I use a customerized cell renderer to display the filterable table header, a customerized cell editor to edit the filterable table header. The cell editor is created like this:
    JTextField textField = new JTextField("");
    DefaultCellEditor cellEditor = new DefaultCellEditor(textField);
    And I add a KeyListener to the textField. The KeyListener can track other keys like "Shift", "Alt", "Ctrl", but it can't track "TAB". It's weird. I also add the KeyListener to JTableHeader, JTable, but when I edit something in the JTextField, I still can't catch the "TAB" key. Have any ideas? Thank you for your time.

    by default the Tab is used (and consumed) by
    focusManager to move focus between components. If you
    want to get it in a component you have to signal the
    manager to keep it's hands off. How to do so depends
    on the jdk version. Focus handling changed
    considerably between 1.3 and 1.4: Prior to 1.4 you
    have to subclass the component in question to return
    true on isManagingFocus(), since 1.4 you have to set
    the comp's focusTraversalKeys to make the manager take
    those instead of the default keys.
    Greetings
    JeanetteThanks Jeanette, it works. I use the Component.setFocusTraversalKeysEnabled(false) to disable all traversal keys of JTextField and add a KeyEventDispatcher to the KeyboardFocusManager. It finally works. Users can use "TAB" keyStroke and "Shift-TAB" keyStroke to traverse in the filterable table header now. Thank you for your great help and the $$ are yours.

  • Swing Tutorial for Java version 1.4.2

    Hi all, where the subject can be found?
    Current tutorial for Swing that is present on site http://java.sun.com/docs/books/tutorial/uiswing/
    is for Java 6 only.
    I am particularly interested in filtering JTable.
    Thanks in advance.

    Here is a link to the 1.5 tutorial which I believe is the same as the 1.4.2 tutorial:
    https://www.cs.auckland.ac.nz/references/java/java1.5/tutorial/uiswing/TOC.html

  • JTable sorting and filtering

    I want to sort and Filter JTable.
    Sample code is avialable for this ?.
    Also i would like to know about 3rd party classes.
    Renjith

    Hi,
    There is a such sample on the tutorials for swing/JTable. In this tutorial, u will find 2 files and then make the corresponding classes :
    TableMap and TableSorter
    u can use them like this :
    TableSorter sorter = new TableSorter(myModel);
    //JTable table = new JTable(myModel); //OLD
    JTable table = new JTable(sorter);
    sorter.addMouseListenerToHeaderInTable(table);
    It is very simple, and you can easily modifie these classes to add filters..
    Regards, JFB

  • JTable allows sorting and filtering at same time

    Hi All:
    Any one has experience about having a JTable allows column sorting and row filtering at same time ?
    I've got JTable allows sorting, as well as a JTable allows filtering; but had a hard time to combine these functionality together. It seems I can't use separate TableModel since I need perform these two operations together on on JTable.
    any help is going to be greatly appreciated!

    Have a look at the QuoteTableModel at www.javapractices.com/Topic162.cjp
    (almost at the bottom of the page)

  • Design Issues for filtering a JTable

    Hi,
    I'm interested in any suggestions on how I should implement a JTable with filtering.
    I have a JTable, which also sorts, so it is associated with a FilterModel as well as a TableModel.
    I have a filter panel with a bunch of controls where a user can type in a name or date range or any number of other fields. This creates a Filter object and I pass this Filter object into my table model.
    Basically the way I thought would be best is if there are two collections within my tableModel. A Filtered collection and a Complete collection. When filtering the filtered collection is filtered and used to display.
    I just can't seem to get it to work yet.
    Does anyone have any ideas for a better approach, or is my approach the standard pattern for doing this kind of thing?
    cheers,
    Oliver

    actually I just had a thought. Within the panel code I could have two data models. One for the filtered stuff and one for the complete stuff :
    table.setModel(completeModel);
    //if user filters
    table.setModel(filteredModel);
    is that a better design?????????

  • How do I get filtered rows from JTable

    Hello,
    I'm using RowSorter to filter my data on a JTable, but now I need to get the rows that were not filtered out so I can export it to a CSV file.
    Any ideas how to accomplish this?
    Thanks,
    Thiago

    According to the javadoc (http://java.sun.com/javase/6/docs/api/javax/swing/table/TableRowSorter.html)
    If you have enabled filtering convertRowIndexToView will return -1 for locations that are not visible in the view.Hopefully you can deduce the rest.

  • Help with Filtering a JTable by multiple columns

    Hi everyone, I need some help with filtering a JTable.
    Basically I have five columns in my table and five text fields for Username, First Name, Last Name, Address and Phone Number.
    What I need to do is have each text field filter the column it is assigned to. So if the table was
    So if I put 'foo' into the username field and two users have a username containing 'foo' they stay on the table, but if i also enter text in first name, say 'john' and only one of those entries has a first name of 'john', the other disappears.
    I'm probably not explaining that very well so let me know if you need clarification.
    I found this code (which I assume works correctly) but I don't know how to interface it with my other class that displays the JTable
    import javax.swing.RowFilter;
    public class UsersFilter extends RowFilter {
         private String[] filters;
         public UsersFilter(String uName, String fName, String lName, String address, String phone) {
              filters = new String[]{uName, fName, lName, address, phone};
        public void setFilter(int column, String filter) {
            if(column < filters.length)
                filters[column] = filter;
        public boolean include(Entry entry) {
            boolean result = true;
            for (int i = 0; i < filters.length; i++) {
                if (result && !(filters.equals("")) ) {
    String v = entry.getValue(i).toString();
    result = v.startsWith(filters[i]);
    return result;

    dbuvid wrote:
    Hi everyone, I need some help with filtering a JTable.For 1.6+, set a RowSorter (which can also do filtering). Details in the 1.6 JavaDocs for JTable.

  • JTable row filtering

    Hi -
    Does anyone have any samples / pointers on implementing custom exclusion filtering of rows in a JTable? I understand that I would use a 'middle' model layer similar to a sortable model, but am having difficulty getting my arms around how to write the model to allow the filtering to be customizable? (i.e. the user could decide to see all rows of a Person table, whose last names are between A and D, but then could turn around and perform another filter to see only rows of Person's between the ages of 10-25.).
    Thanks,
    Kelly

    I've never used them for filtering, but I think the couple TableMap/TableSorter can help you.
    I've used for sorting purpose, and they work properly.
    You'll find them somewhere in the jdk's doc or guide

  • Filtering the rows of a JTable based on JCombobox selection

    Hi,,,
    I write an application where I have a combobox contains the JTable first column data when i click on the item it should give me the rows, which contains the selected item as their first column data. I am enable to get the list like that, please, help me in this.........................................
    Thanks In Advance,
    Sun_sgrk

    Hi Albert,
    I write the code like this.............., please, check it, if I am following any where wrong let me know.......
         JComboBox filterCb=(JComboBox)evt.getSource();
            if(filterCb==filterComboBox){
                for(int i=0;i<wtOb.length;i++){
                    for(int j=0;j<4;j++){
                        if(wtOb[0].toString()==filterComboBox.getSelectedItem())
    System.out.println(""+wtOb[i][j]);
    This code I written in netbeans, when I am printing the values of wtOb[i][j] in console its getting the rows, suppose I am selecting the topic as GeneralTopic then its givining me the output as-----
    GeneralTopic
    Dealer5
    Player3
    BlackJack2
    GeneralTopic
    Dealer7
    Player6
    BlackJack
    but I am getting the trouble when i want to show these rows only in my table, please, give me any suggestion or any help to resolve it. I tried with table.setModel also but its not working.
    Regards,
    sun_sgrk

  • JTable filtering based on comparison of values in a row

    I need to implement a RowFilter that will make its 'include' decision by comparing values in two columns of a JTable row. All the RowFilter.getxxxFilter() methods I see require external input, for example:
    RowFilter.numberFilter(ComparisonType.EQUAL, 10, 1, 2);as I understand it, this filter will filter out all rows that do not contain the value 10 in column index 1 or 2. What I need is something like:
    RowFilter.numberFilter(ComparisonType.BEFORE, 1, 2);Where it will only include rows where the value in column 1 is less than the value in column 2.
    Does RowFilter support this without having to write my own RowFilter subclass? It looks easy enough to write, but I wanted to make sure I understood the API correctly before I go reinventing the wheel.

    nice day,
    I pretty not sure what is comparing values in two columns of a JTable row but maybe this one can hepl you import java.util.*;
    import javax.swing.table.*;
    public class SortableTableModel extends DefaultTableModel {
        private static final long serialVersionUID = 1L;
        private int[] indexes;
        private TableSorter sorter;
        public SortableTableModel() {
        public SortableTableModel(int row, int col) {
            super(row, col);
        @Override
        public Object getValueAt(int row, int col) {
            int rowIndex = row;
            if (indexes != null) {
                rowIndex = indexes[row];
            return super.getValueAt(rowIndex, col);
        @Override
        public void setDataVector(Object[][] dataVector, Object[] columnIdentifiers) {
            indexes = null; // crucial reset.
            super.setDataVector(dataVector, columnIdentifiers);
        @Override
        public void setValueAt(Object value, int row, int col) {
            int rowIndex = row;
            if (indexes != null) {
                rowIndex = indexes[row];
            super.setValueAt(value, rowIndex, col);
        public void sortByColumn(int column, boolean isAscent) {
            if (sorter == null) {
                sorter = new TableSorter(this);
            sorter.sort(column, isAscent);
            fireTableDataChanged();
        public int[] getIndexes() {
            int n = getRowCount();
            if (indexes != null && indexes.length == n) {
                return indexes;
            indexes = new int[n];
            for (int i = 0; i < n; i++) {
                indexes[i] = i;
            return indexes;
       public class TableSorter {
           private SortableTableModel model;
            public TableSorter(SortableTableModel model) {
                this.model = model;
            //n2 selection
            public void sort(int column, boolean isAscent) {
                int n = model.getRowCount();
                int[] indexes = model.getIndexes();
                for (int i = 0; i < n - 1; i++) {
                    int k = i;
                    for (int j = i + 1; j < n; j++) {
                        if (isAscent) {
                            if (compare(column, j, k) < 0) {
                                k = j;
                        } else {
                            if (compare(column, j, k) > 0) {
                                k = j;
                    int tmp = indexes;
    indexes[i] = indexes[k];
    indexes[k] = tmp;
    public Class<?> getColumnClass(int column) {
    return model.getValueAt(0, column).getClass();
    // comparators
    public int compare(int column, int row1, int row2) {
    Object o1 = model.getValueAt(row1, column);
    Object o2 = model.getValueAt(row2, column);
    if (o1 == null && o2 == null) {
    return 0;
    } else if (o1 == null) {
    return -1;
    } else if (o2 == null) {
    return 1;
    } else {
    Class<?> type = getColumnClass(column);
    if (type.getSuperclass() == Number.class) {
    return compare((Number) o1, (Number) o2);
    } else if (type == String.class) {
    return ((String) o1).compareTo((String) o2);
    } else if (type == Date.class) {
    return compare((Date) o1, (Date) o2);
    } else if (type == Boolean.class) {
    return compare((Boolean) o1, (Boolean) o2);
    } else {
    return ((String) o1).compareTo((String) o2);
    public int compare(Number o1, Number o2) {
    double n1 = o1.doubleValue();
    double n2 = o2.doubleValue();
    if (n1 < n2) {
    return -1;
    } else if (n1 > n2) {
    return 1;
    } else {
    return 0;
    public int compare(Date o1, Date o2) {
    long n1 = o1.getTime();
    long n2 = o2.getTime();
    if (n1 < n2) {
    return -1;
    } else if (n1 > n2) {
    return 1;
    } else {
    return 0;
    public int compare(Boolean o1, Boolean o2) {
    boolean b1 = o1.booleanValue();
    boolean b2 = o2.booleanValue();
    if (b1 == b2) {
    return 0;
    } else if (b1) {
    return 1;
    } else {
    return -1;
    or
    my questions about  [http://forums.sun.com/thread.jspa?threadID=5441676&messageID=11003473#11003473]
    Edited by: mKorbel on Jul 2, 2010 4:01 AM
    Edited by: mKorbel on Jul 2, 2010 4:12 AM
    and move Comparator action quasi to the end of the EDT (SwingUtilities.invokeLater(Runable run);)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTable and filtering

    Hi,
    is it possible to filter data in a JTable? For example, if the user only wants to view data that contains "TOM" in the firstname column, then only rows with TOM will be displayed on the table.
    How can implement that? Would I need different tablemodels for different user's selections?

    Yes, it is possible. I've actually used two methods. In the first (and most complex), I built another (filter) jtable which contained field, operator, operand values for each field(column) in my other (data) jtable. The data jtable was actually populated from a SQL table which contained values which were not in the (data) jtable. The rows from the (filter) jtable were saved to the database and a stored procedure parsed it to create a query while was run against the data, which populated the (filter) jtable. The rows were joined by 'and'. They now want me to change this into a full blown query tool ((col1 > 14 or col1<3) and (col2=6 or col2=8)). EEK!
    In the second, I had a predefined filter (i.e. somecolumn > 14) which was turned on & off via a checkbox. In this one, I passed a vector to the tablemodel and the tablemodel built another vector which was used to display.
    Hope this helps.

  • Filtering in JTable

    can anyone help me on this?? how do i filter the "timestamp" data in my JTable???? for example, after filter it out, the data should be range from "22 03 2002 10:46:28" to "25 03 2002 10:46:28".
    can anyone has code to provide me?? thanks in advance.

    hi ,
    u dont have to delete the old data instead what u can do is ,
    construct a new Object [] or Vector for ur data ,
    fill it with ur fresh data and
    if ur using default table model
    set the dataA to the model ur using,
    model. setDataVector(data,columnnames);
    set the model to the table
    table.setModel(model);
    u r model automatically notifies the view ie table internally , and the latest data is shown , nothing else u need to do.

  • How to hide row in JTable?

    Hi all,
    How to hide some specific rows in JTable for user view filtering purpose?
    Thanks

    Try to use the Table Model.
    The "getValueAt" Methode decide what to Display.
    So a simple "if" command can hide the complete row - or a single Statement.
    public Object getValueAt(int row, int col) {
    ArrayList al = new ArrayList();
    StueliTeil tabellenzeile = (StueliTeil) getDaten().get(row);
    switch (col) {
    case 0 :
    return tabellenzeile.getUmfang();
    case 1 :
    return tabellenzeile.getTakt();
    ...

  • How to force update jtable display

    I am trying to add some filtering funtionality to my swing application that uses a JTable. What I do is to filter the JTable's datamodel, and call repaint() on the jtable and JPanel, and do jframe.pack(); Sometimes it works, sometimes it doesn't. I check the jtable model, and it is being updated properly. I guess it is a GUI update problem. Is there a better way to force the whole app's GUI to be updated?
    //update tableModel
    //repaint() jtable;
    //repaint() jpanel;
    jf.pack();

    A couple questions
    1. Did you write your own table model? Not calling fireTableDataChanged() can cause problems in this case.
    2. Do you update the table from a thread? You might need to put the updates on the event thread (SwingUtilities.invokeNoow() or invokeLater()) or manually call fireTableDataChanged() (I'm not sure if this needs to happen on the event thread)

Maybe you are looking for

  • Looking for a particular UI element

    Hello, At htmlb and in many SAP apps there is the following UI: An input field with a little square besides it. Pressing the suqare opens date navigator and selecting a certain date sets it inside the input field. Is there such a ready-made UI at Dyn

  • Music store music will no longer play

    i recently had my mac serviced by apple and when i got it back some of my music that i purchased from the itunes music store no longer works on my computer. It says that 5 or more poeple have the song and I KNOW only 3 people tops have these songs. S

  • Word Document generation using Perl programming on Windows Server 2003 R2

    Hello, Our application generates word document based on pre-defined template on Windows Server 2003 using Perl Scripting. Configuration data is fetched from the database and document is populated based on the template. Sections in the document are id

  • Playing purchased movies on my tv

    Hi Might seem a silly question but if I buy a movie on iTunes how can I watch it on a bigger screen I.e TV or projector? Thanks

  • Adding New Applications to Voice Command on N95

    Is there a way of adding new applications to the list of available applications that could be controlled by Voice Command? I appear to have a pre-configured list that I can't add too. I'd like to be able to activate Google Maps for example, but that