Java Swing GUI

How to Change Background Color of JTable Cell on Mouse Click

In this tutorial, we are going to see how to change the color of a JTable cell on mouse click. In the following code, we will change the background color of a cell during a click event, using the following code textBox.setBackground(Color.BLUE);. when you click on JTable cell, the background of that cell will be blue. This solution is just to give you a basic idea; you can modify it as you wish.


Java Program to Change Color of JTable Cell on Mouse Click:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

class JtableColor extends JFrame
  private JPanel panel;
  private JTable table;
  private JScrollPane scrollPane;
  private String[] columns = new String[3];
  private String[][] data = new String[3][3];
  JTextField textBox = new JTextField();

  public JtableColor()
    //set the title of JFrame
    setTitle("JTable Example");
    //set the size of JFrame
    //Create a panel
    panel = new JPanel();
    //define layout manager
    panel.setLayout(new BorderLayout());
    //add panel to frame
    //JTable Header 
    columns = new String[] {"Column 1" ,"Column 2", "Column 3"};
    //data for JTable in a 2D table
    data = new String[][]
    //Create the model
    TableModel model = new myTableModel();
    //Create a table
    table = new JTable();
    //set row height
    //set the model
    //get the second column
    TableColumn col = table.getColumnModel().getColumn(1);
    //set the editor
    col.setCellEditor(new DefaultCellEditor(textBox));
    //enable selection of JTable cell
    scrollPane = new JScrollPane(table);
    //add JTable to panel
    //Events on JTable cell
    table.addMouseListener(new java.awt.event.MouseAdapter()  
      public void mouseClicked(java.awt.event.MouseEvent e)

  public class myTableModel extends DefaultTableModel
    myTableModel() {

    public boolean isCellEditable(int row,int cols) {
      return true;

  public static void main(String args[])
    JtableColor frame = new JtableColor();


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *