Java Search and Highlight a JTable Cell

How to Search and Highlight Cells in a JTable Using Java NetBeans

Java Search and Highlight a JTable cell



In this Java Tutorial we will go step by step on How To Make a Search and Highlight Form.
This form include a JTextField, JButton and a JTable.
When the user enters text in the search field and clicks the "Search" button, the application searches through the table for matching entries and highlights them with a yellow background. If the search text is cleared, the highlighting is removed.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

Create the Main Class: A class named Table_Search is created, which extends JFrame, representing the main window of the application.
- Constructor (Table_Search()): Set the title, close operation, size, and location of the main frame. Call the initialize() method initialize the user interface components.
- Create the Initialize Method (initialize()): A method to set up the user interface components.
- Create the Search ActionListener (searchActionListener):Implements the ActionListener interface to handle the search button's click event.
- Create the HighlightTableCellRenderer: Extends DefaultTableCellRenderer to customize the appearance of table cells.
- Create the Main Method (main): Show the form.




Project Source Code:


package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;


public class Table_Search extends JFrame {

    private JTextField searchField;
    private JTable table;
    
    public Table_Search(){
        
        setTitle("Table Search");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);
        
        // initialize user interface
        initialize();
        
    }
    
    private void initialize(){
        // Create and configure the search components
        searchField = new JTextField(20);
        JButton searchButton = new JButton("Search");
       searchButton.addActionListener(new searchActionListener());
       JPanel searchPanel = new JPanel();
       searchPanel.add(searchField);
       searchPanel.add(searchButton);
       
       // Create and configure the table model
       DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{
       
    // Sample data rows
    {"John", "Developer", 28},
    {"Alice", "Designer", 24},
    {"Bob", "Manager", 32},
    {"Eve", "Engineer", 29},
    {"Charlie", "Analyst", 27},
    {"Grace", "Architect", 31},
    {"Daniel", "Tester", 25},
    {"Carl", "Engineer", 29},
    {"John", "Analyst", 27},
    {"Rafael", "Architect", 31},
    {"Daniel", "Tester", 25},
    {"Olivia", "Consultant", 26},
    {"Michael", "Programmer", 30},
    {"Sophia", "Product Manager", 33},
    {"David", "Data Scientist", 28},
    {"Emma", "Project Manager", 29},
    {"William", "UX/UI Designer", 24},
    {"Ava", "Software Engineer", 27},
    {"James", "Business Analyst", 31}
           
       }, new String[]{"Name","Job","Age"});
       
       // Create the table using the table model
       table = new JTable(tableModel);
       table.setDefaultRenderer(Object.class, new HighlightTableCellRenderer());
       JScrollPane scrollPane = new JScrollPane(table);
       
       // Set up the layout for the JFrame
       getContentPane().setLayout(new BorderLayout());
       getContentPane().add(searchPanel, BorderLayout.NORTH);
       getContentPane().add(scrollPane, BorderLayout.CENTER);
    }
    
    private class searchActionListener implements ActionListener{
        
        @Override
        public void actionPerformed(ActionEvent e){
            String searchText = searchField.getText();
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            
            // Loop through all rows and columns in the table
            for(int row = 0; row < model.getRowCount(); row++){
                for(int column = 0; column < model.getColumnCount(); column++)
                {
                    String cellValue = String.valueOf(model.getValueAt(row, column));
                    // If the cell value matches the search text, select the cell
                    if(cellValue.equals(searchText))
                    {
                        table.changeSelection(row, column, false, false);
                    }
                    // If the search text is empty, deselect the cell
                    else if(searchText.equals("")){
                        table.changeSelection(row, column, false, false);
                    }
                    
                    // If the search text is empty, deselect the cell
                    else{
                        table.changeSelection(row, column, false, false);
                    }
                }
            }
            
        }
        
    }
    

    
    private class HighlightTableCellRenderer extends DefaultTableCellRenderer{
        
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, 
                boolean isSelected, boolean hasFocus, int row, int column){
        
              Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              String searchText = searchField.getText();
              String cellValue = String.valueOf(value);
              
              // Highlight the cell with yellow background if the cell value matches the search text
              if(cellValue.equals(searchText)){
                  c.setBackground(Color.orange);
              }
              else{ c.setBackground(table.getBackground()); }
              
              return c;
        
        }
        
    }
    
    
    public static void main(String[] args){
        SwingUtilities.invokeLater(()->{
        
            Table_Search tableSearch = new Table_Search();
            tableSearch.setVisible(true);
        
        });
    }
    
    
}




The Final Result:


Java JTable

How to Search and Highlight Cells in a JTable Using Java NetBeans

Search and Highlight JTable Cells in Java NetBeans

Java Search and Highlight a JTable cell

Java Search and Highlight a JTable cell







Share this

Related Posts

Previous
Next Post »