currently the JTable cell is selected on first click, and on the second one it is edited.
Is it possible to directly edit it on the first click?
In the DefaultCellEditor api there is a method named setClickCountToStart
DefaultCellEditor singleclick = new DefaultCellEditor(new JTextField());
singleclick.setClickCountToStart(1);
//set the editor as default on every column
for (int i = 0; i < table.getColumnCount(); i++) {
table.setDefaultEditor(table.getColumnClass(i), singleclick);
}
The posted answer regarding extending DefaultCellEditor does work, and I have used it, except that on changing our application's Look&Feel to Nimbus, the thicker default JTextField border encroaches into the table cell making the text within unreadable.
The reason is that the default table cell editor is JTable$GenericEditor not DefaultCellEditor (of which it is a direct subclass) and the former has the following crucial line in getTableCellEditorComponent()
:
((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
JTable$GenericEditor is package private so can't be subclassed, but JTable provides a getDefaultEditor()
method, so all I do is:
((DefaultCellEditor) myJTable.getDefaultEditor(Object.class)).setClickCountToStart(1);
or if you wanted to cater for all possible columnClasses in your table (in case one of your columns was a Number for example):
for (int i = 0; i < myJTable.getColumnModel().getColumnCount(); i++) {
final DefaultCellEditor defaultEditor = (DefaultCellEditor) myJTable.getDefaultEditor(myJTable.getColumnClass(i));
defaultEditor.setClickCountToStart(1);
}
UsesetClickCountToStart(1)
on the cell editor.
精彩评论