TableCellEditor:如果按下键,则清除原始文本;如果没有投入,保留价值 [英] TableCellEditor: clear original text if key is pressed; retain value if no input was givien

查看:145
本文介绍了TableCellEditor:如果按下键,则清除原始文本;如果没有投入,保留价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个我在stackoverflow中找到的代码,该代码允许表具有一个自定义单元格编辑器作为JTextField.

I have here a code I found in the stackoverflow which allows the table to have a custom cell editor as JTextField.

我一直在阅读一些有关单元格编辑器的文章,并且了解每种抽象方法的行为.

I have been reading some of the articles about cell editor and I understand some the behavior of each abstract method.

class tableText extends AbstractCellEditor implements TableCellEditor {
JComponent component = new JTextField();

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,int rowIndex, int vColIndex) {
    ((JTextField) component).setText((String) value);
    return component;
}

public Object getCellEditorValue() {
    return ((JTextField) component).getText();
}

}

当我要编辑表中的单元格时,此代码允许我添加JTextField,但是我想向其中添加一些代码,但我不确定要放在哪里.

This code allowed me to add a JTextField when I want to edit a cell in my table but I am looking to add some code to it but Im not exactly sure where to put them.

我想添加的行为是这样的:

The behavior I wanted to add was this:

单击该单元格并显示JTextField时,如果用户按下数字键,它将用新的值替换旧的值.

When the cell is clicked and the JTextField appears, if the user pressed a numerical key, it will replace the old value with a new one.

如果该单元格的值保留为空白,则将保留原始值.

If the cell's value was left blank, the original value will be retained.

我知道如何编写这些代码,但是我不确定将它们放在哪里.

I know how to make these codes, but I'm not sure where to put them.

有人可以指导我吗?

推荐答案

如果用户按下数字键,它将用新的值替换旧的值.

If the user pressed a numeric key, it will replace the old value with a new one.

此处所示,您应该为单元格编辑器使用DefaultCellEditorJTextField.覆盖表的editCellAt()方法并选择编辑器的文本,以便在用户键入时立即替换旧值.

As shown here, you should use a DefaultCellEditor with a JTextField for your cell editor. Override the table's editCellAt() method and select the editor's text so that the old value will be replaced immediately as the user types.

final Component editor = getEditorComponent();
…
((JTextComponent) editor).selectAll();

如有必要,将 DocumentListener 添加到检查单个击键或 DocumentFilter 强制执行数字输入.

If necessary, add a DocumentListener to examine individual keystrokes or a DocumentFilter to enforce numeric entry.

如果该单元格的值保留为空白,则将保留原始值.

If the cell's value was left blank, the original value will be retained.

Escape 键可取消编辑并恢复原始值.

Press the Escape key to cancel editing and restore the original value.

这篇关于TableCellEditor:如果按下键,则清除原始文本;如果没有投入,保留价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆