swingjython

Control Edit Properties of JTable in Jython


How would I be able to set certain columns of a JTable to be editable/not editable in Jython?

My table:

self.table_data = []
data_model = DefaultTableModel(self.table_data, self.colnames)
self.table = JTable(data_model)

self.table_pane = JScrollPane()
self.table_pane.setPreferredSize(Dimension(480,370))
self.table_pane.getViewport().setView(self.table)

Solution

  • You can do this with Jython by extending the isCellEditable method of the DefaultTableModel class:

    from javax.swing.table import DefaultTableModel
    class CustomTableModel(DefaultTableModel):
        def isCellEditable(self, row, column):
            # Make column with index 1 (second column) uneditable
            if column == 1:
                return False
            return True
    data_model = CustomTableModel(self.table_data, self.colnames)
    self.table.setModel(data_model)
    

    In this example, all columns would editable except the second column (index 1), and of course, the isCellEdited logic can be refined for any specific cell or column. Just use if and elif statements to set conditions that return True if the cell is to be editable or False if the cell is to be not editable. Finally, set a default return of either True or False if none of the conditions are met.