键绑定和KeyListeners的区别 [英] Difference between KeyBindings and KeyListeners

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

问题描述

什么是键绑定的点,如果你可以只是做:

What is the point of KeyBindings if you could just do:

// Imports

public void Test {
    JButton button1;
    JButton button2;
    JButton button3;
    ...

    Test() {
        button1 = new JButton();
        button1.addKeyListener(this);

        button2 = new JButton();
        button2.addKeyListener(this);

        button3 = new JButton();
        button3.addKeyListener(this);

        ...
    }

    public void keyPressed(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {

        Object src = e.getSource();

        if (src == button1) {
            ...
        }

        else if (src == button2) {
            ...
        }

        else if (src == button3) {
            ...
        }
        ...
    }
}

让我们说我有 10 按钮。然后,如果你使用的键绑定,你必须为每个按钮单独的按键绑定。是不是我给的例子更有效率?为什么不呢?

Let's say I have ten buttons. Then if you use KeyBindings, you would have to make a separate keybinding for each button. Isn't the example I showed more efficient? Why not?

推荐答案

如果您是纯粹的CPU计算周期,是的,它是(可以说)更高效(并经过慎重考虑,我甚至不能确定的那个)。但也有一些长处反对:

If your are purely counting CPU-cycles, yes it is (arguably) more efficient (and after careful consideration, I am not even sure of that). But there are some strong points against it:


  1. 它使你的code相当难看(想象一下,你有成千上万的测试)

  2. 这是可重复使用的少

  3. 少的面向对象:它是一个对象的KeyStroke绑定到对象的行动(详见上操作的这里

  4. 它更容易出错,因为你的code是不易阅读,可以成为巨大的

  5. 您$​​ C $ C是紧耦合(你也很难将你的KeyListener在一个单独的类)

  6. 在您的测试,你检查哪个按钮触发的事件,但你还不知道哪个键是输入。你将不得不增加更多的测试,发现了这一点。

因此​​,对于非常局部问题,你的方法可以是足够的,而对于更大的视图,它不能容纳

So for very localized problems, your approach can be sufficient, while for a bigger view, it cannot hold.

您可以在第三段找到这里,一些在这个问题上相似,补充意见。

You can find in the third paragraph here, some similar and additional comments on this matter.

最后,这是一个有点怪把一个KeyListener的上一个JButton。通常情况下,我们注册一个ActionListener。

Finally, it is a bit weird to put a KeyListener on a JButton. Usually, we register an ActionListener.

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

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