java 单击以编辑 JTable 单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7387099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:45:00  来源:igfitidea点击:

Single click to edit a JTable Cell

javaswingjtable

提问by Akash

currently the JTable cell is selected on first click, and on the second one it is edited.

当前 JTable 单元格在第一次单击时被选中,在第二次单击时被编辑。

Is it possible to directly edit it on the first click?

是否可以在第一次单击时直接对其进行编辑?

回答by Neifen

In the DefaultCellEditor api there is a method named setClickCountToStart

在 DefaultCellEditor api 中有一个名为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);
    } 

回答by Matthew Wise

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.

关于扩展 DefaultCellEditor 的已发布答案确实有效,我已经使用了它,除了将我们的应用程序的外观和感觉更改为 Nimbus 时,较厚的默认 JTextField 边框侵入表格单元格,使文本无法阅读。

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():

原因是默认的表格单元格编辑器是 JTable$GenericEditor 而不是 DefaultCellEditor(它是它的直接子类)并且前者在 中有以下关键行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:

JTable$GenericEditor 是包私有的所以不能被子类化,但是 JTable 提供了一个getDefaultEditor()方法,所以我所做的就是:

((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):

或者,如果您想满足表格中所有可能的 columnClasses(例如,您的一列是数字):

for (int i = 0; i < myJTable.getColumnModel().getColumnCount(); i++) {
    final DefaultCellEditor defaultEditor = (DefaultCellEditor) myJTable.getDefaultEditor(myJTable.getColumnClass(i));
    defaultEditor.setClickCountToStart(1);
}

回答by Petar Minchev

UsesetClickCountToStart(1)on the cell editor.

使用setClickCountToStart(1)的单元格编辑器。