Question

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.

Was it helpful?

Solution

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!

OTHER TIPS

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top