键绑定和按住键 [英] key-bindings and holding down keys

查看:99
本文介绍了键绑定和按住键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为JTextArea组件创建了一个键绑定.调用时,它会创建自己的新实例并为其设置焦点.

I have created a key binding for a JTextArea Component. When invoked, it creates a new instance of itself and sets focus to it.

如果按住Enter键(它会调用键绑定),我的程序将开始吐出一堆JTextArea实例.

If you hold down the enter (which invokes key binding) my program will start spitting out bunch of JTextArea instances.

是否有一种方法可以强制用户再次按Enter键以创建新实例?

Is there a way to force the user to press enter againg to create a new instance?

我可以切换到KeyListeners还是可以使用键绑定?

Do I have I switch to KeyListeners or is there a way with key bindings?

推荐答案

使用键绑定的方法是执行两个操作:

the way to do it with keybindings is to have two actions:

  • 创建组件的操作已绑定到按下的Enter上,它在插入组件时会自行禁用
  • 再次启用该操作的操作已绑定到已释放的回车

一些代码:

// the action to create the component
public static class CreateAction extends AbstractAction {

    private Container parent;
    private Action enableAction;

    public CreateAction(Container parent) {
        this.parent = parent;
        enableAction = new EnableAction(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        setEnabled(false);
        Component field = createTextField();
        parent.add(field);
        parent.revalidate();
        field.requestFocus();
    }

    int count;
    private Component createTextField() {
        // just for fun counting the fields we create
        JTextField field = new JTextField("field: " + count++, 20);
        field.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), 
                "createComponent");
        field.getActionMap().put("createComponent", this);
        field.getInputMap().put(KeyStroke.getKeyStroke("released ENTER"), 
                "enableCreation");
        field.getActionMap().put("enableCreation", enableAction);
        return field;
    }

}

// the action that enables another
public static class EnableAction extends AbstractAction {

    Action toEnable;

    public EnableAction(Action toEnable) {
        this.toEnable = toEnable;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        toEnable.setEnabled(true);
    }

}

// usage
final JComponent parent = new JPanel(new MigLayout("wrap"));
// here I'm lazy and let the action create the very first component as well
add.actionPerformed(null);
add.setEnabled(true);

请注意,动作的相同实例已注册到所有组件,因此哪个焦点(最终再次启用创建)都没有关系

Note that the same instances of the actions are registered to all components, so it doesn't matter which has the focus (and ultimately enables the creation again)

这篇关于键绑定和按住键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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