Search code examples
javaswingjtablejtextfield

Select A row from Jtable based on Jtextfield Input


I have a JTable displaying contents in this format:

Part Number    Quantity   Price
SD1131            7       1,000
SD6534            6       2,000

On the same frame I have a JTextfield(txtNo). I need it such that when the user types the Part Number on the JTextfield, the corresponding record is selected on the JTable. So far I have only been able to select records based on the row number like this:

txtNo.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent e) {

                int index1 = 0;
                int index2 = 0;
                try {
                    index1 = Integer.valueOf(txtNo.getText());
                    tbStore.setRowSelectionInterval(index2, index1);
                } catch (Exception ae) {
                    ae.printStackTrace();
                }
            }
        });

How can I implement the same method to select the JTable row based on the input of the JTextfield?


Solution

  • You will need to find the item in your table for which the part number is equal to the part number entered in the textfield. Steps to take:

    • Read the contents of your textfield
    • Search the index of the matching element in the TableModel
    • Convert that index to the corresponding row index in the JTable using the convertRowIndexToView method (to take in account sorting, filtering, ... )
    • Use the setRowSelectionInterval method of the JTable to select that row

    As an alternative, you can use the JXTable of the SwingX project which has searching capabilities built-in. The SwingX library also includes a component which allows to search such a JXTable (see JXSearchPanel and JXSearchField)