How can we disable the cell editing inside a JTable in Java?


A JTable is a subclass of JComponent for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can fire TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. By default, we can edit the text and modify it inside a JTable cell. We can also disable the cell editing inside a table by calling the editCellAt() method of JTable class and it must return false.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public final class DisableJTableMouseClickTest extends JFrame {
   private JTable table;
   private JScrollPane scrollPane;
   public DisableJTableMouseClickTest() {
      setTitle("DisableJTableMouseClick Test");
      String[] columnNames = {"Country", "Rank"};
      Object[][] data = {{"England", "1"}, {"India", "2"}, {"New Zealand", "3"}, {"Australia", "4"},       {"South Africa","5"}, {"Pakistan","6"}};
      table = new JTable(data, columnNames) {
         public boolean editCellAt(int row, int column, java.util.EventObject e) {
            return false;
         }
      };
      table.setRowSelectionAllowed(false);
      scrollPane= new JScrollPane(table);
      add(scrollPane);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new DisableJTableMouseClickTest();
   }
}

Output

Updated on: 10-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements