36

When a JTable component is created, cell editing is enabled by default. How can I prevent the user from editing the content of a JTable?

AsksAnyway
  • 890
  • 1
  • 8
  • 21
Parag
  • 7,746
  • 9
  • 24
  • 29
  • 3
    See [*How to Use Tables*](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html). – trashgod Mar 29 '12 at 05:06
  • 1
    Does this answer your question? [How to make a JTable non-editable](https://stackoverflow.com/questions/1990817/how-to-make-a-jtable-non-editable) – Peter Alsen Apr 16 '21 at 23:46

8 Answers8

55

You can create a JTable using following code:

    JTable jTable = new JTable() {
        private static final long serialVersionUID = 1L;

        public boolean isCellEditable(int row, int column) {                
                return false;               
        };
    };

Basically what we are doing here is overriding isCellEditable and always returning false from it. This will make a non editabe JTabel.

Rahul Borkar
  • 2,742
  • 3
  • 24
  • 38
  • If this is all your doing, I don't see a problem with using an anonymous class. – Chase Sep 23 '13 at 16:33
  • 4
    this should be better answer. I dont find anything wrong in using anon class here. Plus user might use different `TableModel` in other location. Upvote! – instinct May 27 '15 at 09:15
  • 2
    +1 @instict because this doesn't affect the table model this is a much better answer in my opinion. Also question: is the serialVersionUID really necessary? – Paul Jun 01 '15 at 04:20
50

A JTable uses an AbstractTableModel object. This is the thing you pass into the constructor of the JTable. You can write your own AbstractTableModel as follows

public class MyTableModel extends AbstractTableModel {

      public boolean isCellEditable(int row, int column){  
          return false;  
      }

}

and then initialize your JTable as

JTable myTable = new JTable(new MyTableModel());
richard
  • 605
  • 5
  • 8
  • 1
    I was trying this code to avoid the user being able to edit a cell's content, which is working find. However, it also avoid the application to change the cell's content, is there any workaround for that particular scenario? – clement Oct 09 '13 at 04:41
30
myTable.setDefaultEditor(Object.class, null);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Aïssa
  • 670
  • 8
  • 10
  • 2
    Maybe you could explain this works and enumerate drawbacks? It seems the semantics are different than the previous answers—i.e. you're setting a null editor. Maybe this is slower because asserting whether or not the table is editable requires following a longer code path? – Jonas G. Drange May 01 '16 at 20:11
  • 4
    This is the simple answer I was looking for. Might not be the best performance wise, but its simplicity is worth it. – Cristian Mar 04 '18 at 15:01
  • 1
    It would be nice to know, how this solution works behind the curtain. – rchrd Jun 02 '21 at 09:35
14

Have you tryed simply:

JTable table = new JTable();
table.setEnabled(false);

About JComponent.setEnabled(boolean) it sayes:

Sets whether or not this component is enabled. A component that is enabled may respond to user input, while a component that is not enabled cannot respond to user input. Some components may alter their visual representation when they are disabled in order to provide feedback to the user that they cannot take input.

When it comes to JTable it doesnt seem to give any visual feedback at all. With the perk of still being able to click on the column headers. And in my implementation the application could still change the contents of the cells.

brat
  • 586
  • 5
  • 17
  • Oops. Just saw that user Siddhu came with same solution here: http://stackoverflow.com/questions/1990817/how-to-make-a-jtable-non-editable?noredirect=1&lq=1. dunno if I should remove it here or leave it, since I dont know which question might be deleted as a duplicate. Sorry, a noob here :o – brat May 20 '17 at 02:04
  • Problem with this is that the user cannot see if any row or cell is selected even after he clicks it. i found using `setDefaultEditor()` to be better than this as it provides a visual feedback when the user selects any row or cell. – anotherGatsby Dec 07 '17 at 18:45
4

Hi I'm working a lot on java so I'm gonna give you my way: There are two possibilities the first under netbeans. Go to customize code and make it like this:

JTArticleJPAddArrticle = new javax.swing.JTable();

JTArticleJPAddArrticle.setBackground(new java.awt.Color(204, 204, 255));

JTArticleJPAddArrticle.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {

},
new String [] {
    "Reference","Libellé","Marque","Prix d'achat","Prix de vente","Quantité","Total","Etat"
}
){
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
}
});



jScrollPane8.setViewportView(JTArticleJPAddArrticle);

My other way is to do it is to make an instance of the table model. This is the second way:

model=new DefaultTableModel(head, 0){

    @Override
    public boolean isCellEditable(int i, int i1) {
        return false; //To change body of generated methods, choose Tools | Templates.
    }

   };
jtable.setmodel(model);

Enjoy this is working well for me. All I want to do is help you guys out because I was helped out a lot earlier.

Fuzzy
  • 3,810
  • 2
  • 15
  • 33
  • These are both the same way. The second code snippet just contains less irrelevant code, which makes it better as an answer. – Micah Stairs Oct 17 '16 at 00:12
  • @MicahStairs in the execution process the first one is better because the class will be compiled easily vs the second one is an override which will take a little more time , but by a design view for the developer the second is better easy maintainable code; – Mohammed Housseyn Taleb Mar 25 '17 at 09:49
1

Well on netbeans you can right click on the table and click on table contents, then you go to the column tab and uncheck the "Editable" checkbox. Greetings!!

Zumi
  • 11
  • 2
0
        tm = new javax.swing.table.DefaultTableModel()
                 {
                      public Class<?> getColumnClass(int column)
                      {
                        switch(column)
                        {
                        case 0:
                          return String.class;
                        case 1:
                          return String.class;
                        case 2:
                          return String.class;
                        case 3:
                          return String.class;
                        case 4:
                          return String.class;
                        case 5:
                              return String.class;
                            case 6:
                              return String.class;
                            case 7:
                              return String.class;
                            case 8:
                              return String.class;
                            case 9:
                                  return String.class;
                                case 10:
                                  return String.class;
                                case 11:
                                    return Boolean.class;

                          default:
                            return String.class;
                        }
                      }

                      @Override
                      public boolean isCellEditable(int row, int column) {
                         /* Set the 11th column as editable and rest non-
                              editable */
                          if(column==11){
                              return true;
                          }else{
 //all other columns to false
                         return false;
                          }
                      }
                    };
    table = new javax.swing.JTable(tm);

In this method "isCellEditable" we can enable and disable user edit for particular column. In this case enable column=11 and disable rest of the column

Kavitha yadav
  • 555
  • 5
  • 5
  • Please [edit](https://stackoverflow.com/posts/49110309/edit) your answer to explain why this piece of code answers the question. – André Kool Mar 05 '18 at 12:33
0

I know I am late but hope someone get use of this. You can simple add mouse listener like this:

jtable.addMouseListener( new MouseAdapter () {
    @Override
    public void mouseClicked ( MouseEvent e ) {
        columnIndex = replacedAssets.getSelectedColumn ();
        System.out.println ( "Double click on jtable" );
        if ( columnIndex == 1 || columnIndex == 2 ) {
            JOptionPane.showMessageDialog ( parent , "Editing this Field may cause error in the data." , "Error Edit Not Permitted For This Field" , JOptionPane.ERROR_MESSAGE );
        }
    }
});

this code prevent editing the columns of indexes 1 and 2 you can remove the if condition to make this work for all columns.

Sparks
  • 496
  • 7
  • 16