Question

I'm trying to implement a JTable which has to obey the following rules:

  1. Only the 3'rd column's cells can be edited.
  2. When double clicking any cell in row X, the 3'rd column of row X will start edit.
  3. Whenever start editing a cell, the text inside of it will be selected.

I have a FileTable which extends JTable. In its constructor I have this lines:

getColumnModel().getColumn(2).setCellEditor(new FileTableCellEditor());

addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e){
            if (e.getClickCount() == 2){
                int row = rowAtPoint(e.getPoint());
                editCellAt(row, 2);
            }
        }
    } );

My FileTableCell editor is as follows:

public class FileTableCellEditor extends DefaultCellEditor {

public FileTableCellEditor() {
    super(new JTextField());
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    final JTextField ec = (JTextField) editorComponent;     
    String textValue = (String)value;       
    ec.setText(textValue);      
    SwingUtilities.invokeLater( new Runnable() {
        @Override
        public void run() {
            ec.selectAll();
        }
    });     

    return editorComponent;
}
}

My problem is when I double click on a cell which is not from the 3'rd column, The text edited on the 3'rd columns is not highlighted as selected text.

picture http://www.nispahit.com/stack/tableNotHighlight.png

This is very odd to me, because I know the text is selected. When I write something it removes the text that was in that cell before. It just doesn't what is selected. Oddly, when I double click the 3'rd column cell itself, it does highlight the selection.

picture http://www.nispahit.com/stack/tableHighlight.png

Can someone pour some light?

Thanks!

Was it helpful?

Solution 2

Your JTextField does not highlight the selection because it is not focused. Just add a ec.requestFocus(); right after ec.selectAll();. Then it works as expected.

Explanation: When you click on the editable column Swing will start cell editing (independently of your double-click listener) and forward the initiating event to the component. So the JTextField receives a click and will request focus. When you click on a different column, only your MouseListener initiates cell editing and the event will not get forwarded. (Forwarding the event would not help anyway as the click is outside the text field.) So you have to request the focus manually.

OTHER TIPS

You can try the Table Select All Editor approach. Don't forget to check out the Table Select All Renderer.

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