how to search an element in a JTable java?

53,135

Solution 1

You probably want to use a RowFilter to filter the search results. Below is an example using a RowFilter and a DocumentListener. When the user types, the rows are filter dynamically.

See RowFilter api and DocumentListener api. If you don't like the dynamic filtering, you could just stick with the button, or you can add an ActionListener to the the JTextField, so when Enter is pressed, the filter will process. The code you would put in the listener call back (actionPerformed) would just be

  String text = jtfFilter.getText();
  if (text.trim().length() == 0) {
     rowSorter.setRowFilter(null);
  } else {
     rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
  }

enter image description here

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class TestTableSortFilter extends JPanel {

    private String[] columnNames
            = {"Country", "Capital", "Population in Millions", "Democracy"};

    private Object[][] data = {
        {"USA", "Washington DC", 280, true},
        {"Canada", "Ottawa", 32, true},
        {"United Kingdom", "London", 60, true},
        {"Germany", "Berlin", 83, true},
        {"France", "Paris", 60, true},
        {"Norway", "Oslo", 4.5, true},
        {"India", "New Delhi", 1046, true}
    };

    private DefaultTableModel model = new DefaultTableModel(data, columnNames);
    private JTable jTable = new JTable(model);

    private TableRowSorter<TableModel> rowSorter
            = new TableRowSorter<>(jTable.getModel());

    private JTextField jtfFilter = new JTextField();
    private JButton jbtFilter = new JButton("Filter");

    public TestTableSortFilter() {
        jTable.setRowSorter(rowSorter);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JLabel("Specify a word to match:"),
                BorderLayout.WEST);
        panel.add(jtfFilter, BorderLayout.CENTER);

        setLayout(new BorderLayout());
        add(panel, BorderLayout.SOUTH);
        add(new JScrollPane(jTable), BorderLayout.CENTER);

        jtfFilter.getDocument().addDocumentListener(new DocumentListener(){

            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = jtfFilter.getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = jtfFilter.getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
               JFrame frame = new JFrame("Row Filter");
               frame.add(new TestTableSortFilter());
               frame.pack();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setLocationRelativeTo(null);
               frame.setVisible(true);
            }

        });
    }
}

Solution 2

The model of a JTable is where the data is held, by searching it you should be able to check if it contains what you want :

for(int i = 0; i < table.getRowCount(); i++){//For each row
    for(int j = 0; j < table.getColumnCount(); j++){//For each column in that row
        if(table.getModel().getValueAt(i, j).equals("STRING_TO_SEARCH")){//Search the model
            System.out.println(table.getModel().getValueAt(i, j));//Print if found string
        }
    }//For loop inner
}//For loop outer

Good luck!

Share:
53,135

Related videos on Youtube

user3332136
Author by

user3332136

Updated on July 09, 2022

Comments

  • user3332136
    user3332136 almost 2 years

    I have made a JTable in java. I can do everything except search an element in my table. I want to work a input dialog so this is what I have at this moment:

    btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {    
                String name = JOptionPane.showInputDialog("Wat wil je zoeken?");
            }
        });
        add(btnSearch);
    

    I thought to do it with a for loop. but I don't know how. Can someone help me pls?

    • Rahul
      Rahul over 10 years
      To create the jtable, you will have used the datatableModel. In that you can perform the search.
  • mKorbel
    mKorbel over 10 years
    then for why reason is RowFilter there
  • mustangDC
    mustangDC almost 9 years
    Thanks. Helped a lot. U deserve more than a Upvote. Cheers
  • user1314776
    user1314776 about 8 years
    Thanks! Excellent example and easy to use!
  • Krismorte
    Krismorte about 7 years
    Thanks! Works perfect for me
  • aurelianr
    aurelianr over 6 years
    this is the good example because the user ask for searching and not for filtering. When you want to search for a record from a jtable you want that record to be automatically selected and the other rows of the table to be visible. When you filter the jtable the only visible rows are the rows which contains the input keyword.

Related