java - 按键时的 JTable 编辑

标签 java swing jtable

我正在尝试通过按键以编程方式开始编辑 JTable 中当前行的第三列。

我已经实现了一个 KeyListener,它在 keyReleased() 中包含此代码

if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
    myTab.changeSelection(myTab.getSelectedRow(), 2, true, false);
    myTab.editCellAt(myTab.getSelectedRow(), 2);
}

当我松开 Enter 时,单元格确实是可编辑的(我可以在末尾键入),但没有插入符号。

当我用鼠标单击时,行为符合预期(我可以编辑并且存在插入符号)。

此外,我注意到在 keyrelease 上,我的 celleditor 为 null,而在 mouseclick 上它不为 null。

我做错了什么?

最佳答案

避免KeyListener,它在焦点和事件分派(dispatch)顺序方面是不可靠的(有可能在监听器之前使用它们的 key ,因此您永远不会收到通知)。

使用key bindings相反

InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = table.getActionMap();

KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);

im.put(enterKey, "Action.enter");
am.put("Action.enter", new AbstractAction() {
    public void actionPerformed(ActionEvent evt) {
        table.changeSelection(table.getSelectedRow(), 2, false, false);
        if (!table.editCellAt(table.getSelectedRow(), 2)) {
            JOptionPane.showMessageDialog(table, "Failed to start cell editing");
        }
    }
});

我也对这个 myTab.changeSelection(myTab.getSelectedRow(), 2, true, false); 调用表示怀疑。 JavaDocs 基本上说...

toggle: true, extend: false. If the specified cell is selected, deselect it. If it is not selected, select it.

这对我来说,如果当前选择了单元格,它将被取消选择。

已更新工作示例

public class TestTableEditor {

    public static void main(String[] args) {
        new TestTableEditor();
    }

    private JTable table;

    public TestTableEditor() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                table = new JTable(new MyTableModel());
                InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
                ActionMap am = table.getActionMap();

                KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);

                im.put(enterKey, "Action.enter");
                am.put("Action.enter", new AbstractAction() {
                    public void actionPerformed(ActionEvent evt) {
                        table.changeSelection(table.getSelectedRow(), 1, false, false);
                        if (!table.editCellAt(table.getSelectedRow(), 1)) {
                            JOptionPane.showMessageDialog(table, "Failed to start cell editing");
                        }
                    }
                });

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MyTableModel extends AbstractTableModel {

        @Override
        public int getRowCount() {
            return 1;
        }

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            switch (columnIndex) {
                case 0:
                    value = "Can't edit";
                    break;
                case 1:
                    value = "Edit me";
                    break;
                case 2:
                    value = "Can't edit";
                    break;
            }
            return value;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 1;
        }
    }
}

已更新

在所有愚蠢、痛苦、难以找到的事情中......

table.setSurrendersFocusOnKeyrinkle(true); 添加到您的代码中...

Sets whether editors in this JTable get the keyboard focus when an editor is activated as a result of the JTable forwarding keyboard events for a cell. By default, this property is false, and the JTable retains the focus unless the cell is clicked.

关于java - 按键时的 JTable 编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206083/

相关文章:

java - Hibernate 查询不返回新数据

java - 仿射变换如何工作?

java - 如何在 JTabbedPane 中拖动选项卡

java - 如何将自定义 JTable 代码添加到 GUI Builder Netbeans?

java - JTable和Table模型什么时候用什么时候?

java - 在 JTable 中用鼠标移动行

java - 创建一个类和在另一个类中声明一个类有区别吗?

java - Decimalformat:在 JTable 中不需要用逗号替换点

java - 一名 Java 学徒尝试从 System.out.println 迁移到 swing

java - 如何使用 gradle 和 jlink 构建 Java 应用程序?