Solved

Jtable filtering

Posted on 2008-10-11
2
679 Views
Last Modified: 2013-12-22
How to use filter on a particular column if  jtable depending on key stroke. LIke if press A then then only rows matching A as starting character of that particular column should display. If i press AB then starting with AB like this.

Any help appreciated.

Thanks
0
Comment
Question by:techvts
2 Comments
 
LVL 2

Expert Comment

by:Monky42
ID: 22694713
Quick idea:
Add a textfield to the form/panel/frame. Give the textfield focus (so that typing will change the textfield values). Add a listener to the textfield (textfield.getDocument().addDocumentListener(yourListener);) and update your table when the textfield value has been changed.
For JTable filtering there are lots of tutorials out there (e.g. http://www.java2s.com/Code/Java/JDK-6/JTableFiltering.htm)

Good Luck!
0
 

Accepted Solution

by:
mih earned 50 total points
ID: 22911132
There is a good tutorial on the subject of keystroke capture at http://java.sun.com/docs/books/tutorial/post1.0/ui/keylistener.html. However, the following may also help (although will only search on alphanumeric text cell content within the most recently selected table column as it currently stands):

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTable;
 
/**
 * Example (cut-down) implementation of a keyboard listener for
 * providing JTable row selection via keyboard input matches to
 * column content. Additional validation and error checking should
 * be included in any production version.
 * <p>
 * Copyright (c) 2008, Innovation Science Pty Ltd. This software
 * is licensed under the <a href=
 * "http://creativecommons.org/licenses/LGPL/2.1/">
 * CC-GNU LGPL</a> version 2.1 or later.
 * <p>
 * @author MB/MH, Innovation Science Pty Ltd
 * @version 1.0.0
 */
public class ExampleKeyListener extends KeyAdapter
{
  private JTable theTable;
  private long lastKeyTime = 0;
  private StringBuffer currentString;
 
  public ExampleKeyListener ( JTable aTable )
  {
    super();
    theTable = aTable;
    currentString = new StringBuffer();
  }
 
  /**
   * Scrolls to and selects the row of the table associated with this
   * Key Listener instance by matching the sequence of characters
   * pressed during the past two (2) seconds with the contents of 
   * cells in the currently selected table column. The first cell
   * containing text that starts with the search character sequence
   * will determine the row to be selected. No selection change is 
   * made if the character sequence does not match any of the cells
   * in the currently selected table column. 
   */
  public void keyPressed( KeyEvent aKeyEvent )
  {
    // Reset the search string if too much time has elapsed since 
    //  the last key press event
    long currentTime = System.currentTimeMillis();
    if ((currentTime - lastKeyTime) > 2000)
    {
      currentString.setLength( 0 );
    }
    lastKeyTime = currentTime;
 
    // Determine key that caused KeyEvent to be generated
    // *** NOTE THIS SHOULD HAVE ADDITIONAL CHECKING TO ENSURE *** 
    // *** ONLY VALID, SEARCHABLE CHARACTERS ARE CONSIDERED ***
    char keyChar = aKeyEvent.getKeyChar();
    currentString.append( keyChar );
    // Determine the currently selected table column (default to
    // first column)
    int columnIndex = Math.max( theTable.getSelectedColumn(), 0 );
 
    // Loop through each value in the table and check if 
    //  it matches the current String
    int rowCount = theTable.getRowCount();
    String testString = currentString.toString().toLowerCase();
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) 
    {
      String rowValue = ((String)theTable.getValueAt( rowIndex,
                          columnIndex )).toLowerCase();
      if (rowValue.startsWith( testString )) 
      {
        // Scroll to and highlight the matching selection
        theTable.setRowSelectionInterval( rowIndex, rowIndex );
        theTable.scrollRectToVisible( 
            theTable.getCellRect( rowIndex, columnIndex, true ) );
        break;
      }
    }
  }
} 

Open in new window

0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JDeveloper 12c for 32 bit 4 85
java 8 lambda expresssions exception handling 3 91
Java - Why doesn't this JFrame work 3 59
Java: The Public Class Main 4 17
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question