gpt4 book ai didi

swing - 带有 JComboBox 编辑器的 JTable : Is it possible to edit the cell value from keyboard with one key press

转载 作者:行者123 更新时间:2023-12-01 04:20:18 25 4
gpt4 key购买 nike

我有一个包含 JComboBox 编辑器的 JTable 初始化有点像

JComboBox comboBox = ...;
TableColumn tc = table.getColumnModel().getColumn(i);
tc.setCellEditor(new DefaultCellEditor(comboBox));

这在其他方面工作正常,但我希望能够在表格中导航并仅使用键盘更新值。现在可以使用组合框,但如果我想更新值“1”,我必须先按一个键激活组合框,然后按“1”选择项目。

所以,我想要的是我可以按“1”,然后只需按一个键就可以选择该项目。

对于文本单元格,我设法使用 prepareEditor 做到这一点,如下所示......
@Override
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JTextComponent) {
((JTextComponent) c).selectAll();
}
return c;
}

...但我还没有弄清楚如何处理组合框。

一种可能性可能是自己的 TableCellEditor 但如果有一个更简单的解决方案会很好 =)

br,
东子

最佳答案

如果有人仍然感兴趣,我对 Touko 的代码做了一个简单的修改,这对我有用:

public class CustomTable extends JTable {
private static final long serialVersionUID = -8855616864660280561L;

public CustomTable(TableModel tableModel) {
super(tableModel);
}

@Override
public Component prepareEditor(TableCellEditor editor, int row, int column) {
final Component comp = super.prepareEditor(editor, row, column);

// Text component should select all text when initiated for editing.
if (comp instanceof JTextComponent)
((JTextComponent) comp).selectAll();

// Try to obtain focus for the editor component.
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() { comp.requestFocusInWindow(); }
});

return comp;
}
}

所以基本上,我只是在稍后使用 SwingUtilities.invokeLater 请求编辑器组件的焦点。 .这种方法的原因是因为如果编辑器组件尚不可见,焦点请求将失败。

希望这可以帮助任何人。

关于swing - 带有 JComboBox 编辑器的 JTable : Is it possible to edit the cell value from keyboard with one key press,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com