How to make a JTable non-editable

How to make a JTable non-editable

In Java Swing, you can make a JTable non-editable by customizing its cell renderer and cell editor. Here's how you can make a JTable non-editable:

import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; public class NonEditableJTableExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Non-Editable JTable Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a sample data model with sample data DefaultTableModel model = new DefaultTableModel( new Object[][] { {"John", "Doe", 30}, {"Alice", "Smith", 25}, {"Bob", "Johnson", 40} }, new String[] {"First Name", "Last Name", "Age"} ); // Create the JTable with the non-editable model JTable table = new JTable(model) { @Override public boolean isCellEditable(int row, int column) { // Make all cells non-editable return false; } }; // Customize the table appearance table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getTableHeader().setReorderingAllowed(false); JScrollPane scrollPane = new JScrollPane(table); frame.add(scrollPane, BorderLayout.CENTER); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } } 

In this example:

  1. We create a JFrame and set up a sample data model using DefaultTableModel.

  2. We create a JTable and override the isCellEditable method to return false, making all cells non-editable. This is the key step in making the JTable non-editable.

  3. We customize the appearance of the JTable by setting the selection mode, disallowing column reordering, and adding it to a JScrollPane.

By overriding isCellEditable and returning false, you prevent users from editing the cells in the JTable, effectively making it non-editable. You can adapt this approach to your specific use case and data model as needed.


More Tags

sublist unity3d-gui custom-attributes contrast reporting-services webcam arraybuffer wpftoolkit spring-boot sap-basis

More Java Questions

More Gardening and crops Calculators

More Everyday Utility Calculators

More Chemical reactions Calculators

More Financial Calculators