问题
我想要JXTable具有“选择所有内容”的行为。做一个简单的覆盖就可以了,但是RXTable的双击功能不适用于JXTable。使用“按钮操作”模式时可以,但是使用F2或双击JXTable中的某些内容时,RXTable与RXTable冲突并删除选择,因此我将保留默认行为。是由于在内部使用GenericEditor还是其他原因?
我怎样才能让JXTable在F2上选择全部或双击编辑?
编辑:看起来这仅在模型具有为整数类型定义的列时发生。当为String或Object列定义它时,它可以按预期工作。
解
感谢kleopatra的修复,我能够更改selectAll方法,以便它处理JFormattedTextFields和所有编辑情况。由于原始代码可以在类型上进行编辑,因此我仅在其他情况下使用了此修复程序。这就是我最后得到的。
将RXTable中的selectAll替换为以下内容:
/*
* Select the text when editing on a text related cell is started
*/
private void selectAll(EventObject e)
{
final Component editor = getEditorComponent();
if (editor == null
|| ! (editor instanceof JTextComponent
|| editor instanceof JFormattedTextField))
return;
if (e == null)
{
((JTextComponent)editor).selectAll();
return;
}
// Typing in the cell was used to activate the editor
if (e instanceof KeyEvent && isSelectAllForKeyEvent)
{
((JTextComponent)editor).selectAll();
return;
}
// If the cell we are dealing with is a JFormattedTextField
// force to commit, and invoke selectall
if (editor instanceof JFormattedTextField) {
invokeSelectAll((JFormattedTextField)editor);
return;
}
// F2 was used to activate the editor
if (e instanceof ActionEvent && isSelectAllForActionEvent)
{
((JTextComponent)editor).selectAll();
return;
}
// A mouse click was used to activate the editor.
// Generally this is a double click and the second mouse click is
// passed to the editor which would remove the text selection unless
// we use the invokeLater()
if (e instanceof MouseEvent && isSelectAllForMouseEvent)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
((JTextComponent)editor).selectAll();
}
});
}
}
private void invokeSelectAll(final JFormattedTextField editor) {
// old trick: force to commit, and invoke selectall
editor.setText(editor.getText());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
editor.selectAll();
}
});
}
最佳答案
适用于三种选择类型中的两种的快速技巧
// in selectAll(EventObject) special case the formatted early
if (editor instanceof JFormattedTextField) {
invokeSelectAll(editor);
return;
}
private void invokeSelectAll(final JFormattedTextField editor) {
// old trick: force to commit, and invoke selectall
editor.setText(editor.getText());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
editor.selectAll();
}
});
}
How to select all text in a JFormattedTextField when it gets focus?记住了这个技巧-在键入时开始编辑时不处理这种情况,在这种情况下,不会删除内容(对于普通文本字段而言),而是添加了新键。