Azer Rtyu
Azer Rtyu

Reputation: 339

Make a column non-editable in a JTable

I created a MasterDetail Simple Form using Netbeans, and I have a JTable which is related to the database.

I want to edit a column in this JTable to make it non-editable.

I Googled about it and this all I can find :

this.masterTable.getColumn("Validation").setEditable(false);

which won't work with me !

Upvotes: 7

Views: 28462

Answers (6)

Benjamin Ronneling
Benjamin Ronneling

Reputation: 821

If the jtable name is wordListJTable:

        String colTitles[] = {"#", "Word", "Definiton"};
        boolean[] isEditable = {false,true,true};
        wordTableModel = new DefaultTableModel(colTitles, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // make read only fields except column 0,13,14
                return isEditable[column];
            }
        };
        // The 0 argument is number rows. 
        wordListJTable.setModel(wordTableModel);

Upvotes: 0

camickr
camickr

Reputation: 324197

Override the isCellEditable(...) method of the TableModel.

DefaultTableModel model = new DefaultTableModel(...)
{
    @Override 
    public boolean isCellEditable(int row, int column)
    {
        // add your code here
    }
}

JTable table = new JTable( model );

Upvotes: 12

P. Pandey
P. Pandey

Reputation: 108

Here is solution if you are extending JTable directly:(place this code in constructor)

DefaultTableModel tableModel = new DefaultTableModel(data, colNames){

        @Override
        public boolean isCellEditable(int row, int column)
        {
            // make read only fields except column 0,13,14
            return column == 0 || column == 13 || column == 14;
        }
    };

this.setModel(tableModel);

Upvotes: 2

Amarnath
Amarnath

Reputation: 8865

Disabling user edits on JTable for multiple columns

JTable table = new JTable(10, 4) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return column == 3 || column==4 || column==5 ? true : false;
    }
};

Upvotes: 6

Azer Rtyu
Azer Rtyu

Reputation: 339

I found the solution using GUI :

  • Right-click on the table cells.
  • From popup menu, choose "Table Contents..".
  • Uncheck the editable check box for the column you want to make it non-editable.

enter image description here

Upvotes: 5

blackpanther
blackpanther

Reputation: 11486

isCellEditable()

Here is the Javadoc: isCellEditable(int, int) is the method you want. If you are using a TableModel then this method can then be overridden in the subclass of the TableModel for that JTable instance.

Upvotes: 1

Related Questions