我在 JTable 中有一个功能,当用户单击单元格时,它会删除其中的某些字符(例如当有内容 - Hello
时,当用户单击它时,它会显示 Hello
)。当不再编辑时,它会再次显示 - Hello
。
我的问题是,当选择某个单元格(但尚未编辑)并且我开始输入 Hi
时,它不会删除该字符,因此可编辑单元格看起来像 -你好嗨
。
同样的问题是当选择某些单元格并且用户按空格键时。
我想将功能添加到 JTable 中,以便当开始编辑单元格的内容时(通过任何方式 - 选择时单击/键入/空格键/也许还有更多我不知道的选项)关于),我想首先以编程方式更改内容。另一种选择是在选择单元格时将其删除(但是我必须记住最后选定的单元格的位置,以便可以将字符读取到其中)。
我在 TableChangeListener 类的 propertyChange 中尝试过:
table.setValueAt(removeCharacter(table.getValueAt(row,column)), row, column);
但它不起作用,因为单元格已经被编辑并且我无法更改它。
最佳答案
- 您必须使用自己的单元格编辑器实现来满足您自己的一组要求。
- 因此,创建一个实现
FocusLisetener
和ActionListener
的自定义 CellEditor,并实现FocusGained
和FocusLost
函数 - 还实现
actionPerformed
函数来更新输入点击时的值。 - 处理 Focus 事件有点棘手。因为它往往会错误地更新单元格。这就是为什么我必须将引用表作为构造函数参数传递给
CellEditor
并读取单元格行、焦点增益上的 col。 - 要反射(reflect)
- xxxx
:将-
放在单元格值之前,请尝试使用自定义CellRenderer
。查看official tutorial page有关示例的详细信息。部分功劳归功于@mKobel。
实现的自定义单元格编辑器用于指导:将其分配给您的目标表列并进行测试。
我的测试结果的动图:
代码:
class CustomRenderer extends DefaultTableCellRenderer {
public void setValue(Object value)
{
setText("- "+value);
}
}
class MyCellEditor extends AbstractCellEditor
implements TableCellEditor,
FocusListener,
ActionListener
{
JTextField textFeild;
String currentValue;
JTable table;
int row, col;
public MyCellEditor(JTable table) {
this.table = table;
textFeild = new JTextField();
textFeild.addActionListener(this);
textFeild.addFocusListener(this);
}
@Override
public Object getCellEditorValue() {
return currentValue;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
currentValue = (String)value;
return textFeild;
}
@Override
public void focusGained(FocusEvent e) {
textFeild.setText("");
row = table.getSelectedRow();
col = table.getSelectedColumn();
}
@Override
public void focusLost(FocusEvent e) {
if(!textFeild.getText().equals(""))
//currentValue = textFeild.getText();
table.setValueAt(textFeild.getText(), row, col);
fireEditingStopped();
}
@Override
public void actionPerformed(ActionEvent e) {
if(!textFeild.getText().trim().equals(""))
currentValue = textFeild.getText();
fireEditingStopped();
}
}
关于java - 当用户单击时将内容添加到单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273883/