JTextField's setText method doesn't work from a KeyListener

邮差的信 提交于 2019-12-06 05:58:55

This behavior is due to the fact that the KeyEvent will be processed by the field after your KeyListener was fired. You can circumvent it by consuming the event via

ke.consume();

inside your method keyTyped.

Depending on your requirements another way would be to encapsulate the clearing calls inside a SwingUtilities.invokeLater which will be processed after your current event and thus clear the field after it was updated.

Here's a code snippet using key bindings to wipe out all text on pressing 'a', implemented to use actions already registered in the field's action map (note that you still need to wrap the code into SwingUtilities.invokeLater - as Howard already suggested - that guarantees it to be processed after the fields internal processing)

    JTextField normal = new JTextField("just a normal field", 10);
    final Action selectAll = normal.getActionMap().get("select-all");
    final Action cut = normal.getActionMap().get("cut-to-clipboard");
    Action combine = new AbstractAction() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    selectAll.actionPerformed(e);
                    cut.actionPerformed(e);

                }
            });
        }

    };
    normal.getActionMap().put("magic-delete-all", combine);
    normal.getInputMap().put(KeyStroke.getKeyStroke("A"), "magic-delete-all");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!