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

AWTJavaObject Oriented ProgrammingProgrammingSwing

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

raja
Published on 24-Jul-2019 14:11:52
Advertisements