Single click to edit a JTable Cell

走远了吗. 提交于 2021-02-07 11:26:44

问题


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?


回答1:


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



回答2:


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



回答3:


UsesetClickCountToStart(1) on the cell editor.



来源:https://stackoverflow.com/questions/7387099/single-click-to-edit-a-jtable-cell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!