JTable中。删除行。消耗事件不要进一步调度 [英] JTable. Deleting rows. Consume the event to not get dispatched further

查看:254
本文介绍了JTable中。删除行。消耗事件不要进一步调度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在删除按键上删除JTable中的行。所以用例很简单,用户选择一些行,按删除键,行被删除。代码也很简单:

I needed to delete rows from a JTable on the delete key-press. So the use case is quite simple, the user select some rows, press the delete key, the rows get deleted. The code is also very simple :

DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
    int[] selectedRows = table.getSelectedRows();
    for (int i = selectedRows.length - 1; i > -1; i--) {
        tableModel.removeRow(selectedRows[i]);
    }

问题是删除完成后我们会听到声音(我在窗户上,典型的窗口发出哔哔声),就像在空文本框中按下删除键一样(或当插入符号位于文本末尾时)。
我发生的事情是,按键被进一步调度到显示单元格文本内容的文本组件(删除后的第一个单元格)。默认情况下,DefaultEditorKit $ DeleteNextCharAction#actionPerformed方法触发蜂鸣声,因为点前面没有字符。
作为黑客,我在监听器中修改事件:

The problem is that after the deletion gets finished we'll hear a sound beep (I'm on windows, typical windows beep), as when pressing the delete key in an empty text box (or when the caret is at the end of the text). What I thing is happening is that the key press is dispatched further to the text component that displays the text content of the cell(the first cell after the deleted ones). The beep is fired by the DefaultEditorKit$DeleteNextCharAction#actionPerformed method because there is no character ahead the dot. As a hack I modify the event in the listener :

e.setKeyCode(KeyEvent.VK_SHIFT) // see JTable#processKeyBinding

事件没有进一步转发,所以蜂鸣声消失了,但我觉得这很糟糕解决方案,还有一个更好的解决方案。但哪个是更​​好的解决方案?

the event does not get forwarded further, so the beep dissapear but I think it's a bad solution and there's a better one. But which is that better solution ?

推荐答案

使用键绑定代替......

Use key bindings instead...

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

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "DeleteRow");
am.put("DeleteRow", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {

        System.out.println("Delete row");
        int row = table.getSelectedRow();

        if (row > -1) {

            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.removeRow(row);

        }

    }
});

(我为测试借了mKorbel数据,所以我的测试使用的是 DefaultTableModel ,你需要转换为你正在使用的模型。

(I borrowed mKorbel data for my test, so my test was using a DefaultTableModel, you will need to cast to the model you are using).

另外,如果你编辑,这可能仍然会触发,所以你将需要检查

Also, if you editing, this may still fire, so you will need to check for that

这篇关于JTable中。删除行。消耗事件不要进一步调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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