简体   繁体   中英

Single click to edit a JTable Cell

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);
}

在单元格编辑器上使用setClickCountToStart(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM