0

Not really sure how to word the title with out making it a paragraph long.

Basically I have a JTable in my program that I can't let the users edit. But the program must be able to edit it itself. Futhermore, the user must be allowed to actually select and copy text from the cells in the table, just not edit it.

How can I achieve this? Preferably a generic solution so it can be applied to multiple tables within my program with different layouts etc.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
J_mie6
  • 720
  • 1
  • 9
  • 25

2 Answers2

3

In you need to set the selection properties of your table to true, like below. You also have to make sure that the isCellEditable method is overridden and set to false, the AbstractTableModel class does this by default.

  final JTable table = new JTable(new AbstractTableModel() {

        @Override
        public Object getValueAt(int r, int c) {
            return data[r][c];
        }

        @Override
        public int getRowCount() {
            return data.length;
        }

        @Override
        public int getColumnCount() {
            return data[1].length;
        }

    });

    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setCellSelectionEnabled(true);

This will allow the cell to be highlight individually and copied from but will not allow editing of the cell.

EDIT: Changed answer!

Tom
  • 15,798
  • 4
  • 37
  • 48
  • To me this code makes it seem like it can always be edited, which is why I posted a question, all the stuff I have read idn't appear to be the right solution, but I will give it a go. Thanks for the clarification – J_mie6 Dec 18 '12 at 21:07
  • Right, as I suspected this is not what I wanted. I need it so the user can select the text in the cell not the cell itself, and it is unavailable with this method. That is the problem I face – J_mie6 Dec 18 '12 at 21:31
  • Yep, I should have tested that before I replied. However this is a fairly common question and the answer is not hard to find. – Tom Dec 18 '12 at 22:00
  • right! Thanks. I have actually tried to find the answer but Iwas always unsuccessfull oh well at least I have the solution now! – J_mie6 Dec 18 '12 at 22:15
0

Tom's solution allows you to click on a cell and press Ctrl+C to copy its entire contents. If you want to be able to select a region of the text within a cell, you could do:

JTable table = new JTable(...);

JTextField textField = new JTextField();
textField.setEditable(false);
table.setDefaultEditor(String.class, new javax.swing.DefaultCellEditor(textField));

Then make sure your TableModel.isCellEditable returns true for whatever cells you want to be able to copy from.

(You can skip allowing/enabling row/column/cell selection if you go this route.)

Robert Fleming
  • 1,337
  • 17
  • 13