How do I get Integer in JTable cell to be selected when edit using keyboard

I have some cells in a JTable, when I double-click on the cell to edit it the current value (if any) is selected and is replaced by any value I enter, which is the behaviour I want. But when I use the keyboard to navigate to the cell and start editing, new values are added to the end of the current value which is not what I want.

I have created my own IntegerCellEditor (see below) and added a focus event or the textfield used when editing to select all the current text but it has no effect, any ideas please ?

publicclass IntegerCellEditorextends DefaultCellEditor

{

public IntegerCellEditor( JTextField textfield )

{

super( textfield );

//Ensure old value is always selected, when start editing

((JTextField)getComponent()).addFocusListener(new FocusAdapter()

{

publicvoid focusGained(FocusEvent fe){

((JTextField)getComponent()).selectAll();

}});

((JTextField)getComponent()).setHorizontalAlignment(JTextField.RIGHT);

}

/**

* Return as Integer (because delegate converts values to Strings).

*/

public Object getCellEditorValue()

{

return Integer.valueOf((String)delegate.getCellEditorValue());

}

}

[1901 byte] By [paultaylora] at [2007-10-3 8:17:55]
# 1

I'm not sure, but maybe you should override getCellEditorComponent method and call selectAll on your component there.

Maybe it will work then. Just try it.

something like this:

public Component getCellEditorComponent(....

{

((JTextField)super.getCellEditorComponent()).selectAll();

}

mvpa at 2007-7-15 3:23:14 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thanks, your right, added follwoing code

public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column )

{

Component c = super.getTableCellEditorComponent( table, value, isSelected, row, column );

((JTextField)c).selectAll();

return c;

}

paultaylora at 2007-7-15 3:23:14 > top of Java-index,Desktop,Core GUI APIs...
# 3

> But when I use the keyboard to navigate to the cell and start editing,

> new values are added to the end of the current value which is not what I want.

How does the use know that typing will replace the text and not append? Usually if text is to be deleted, it is highlighted to give the user a visual cue.

Here is a renderer that does this, in case your interested:

http://forum.java.sun.com/thread.jspa?forumID=57&threadID=752727

camickra at 2007-7-15 3:23:14 > top of Java-index,Desktop,Core GUI APIs...