Difference between KeyBindings and KeyListeners

可紊 提交于 2019-12-04 04:30:04

问题


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) {
            ...
        }
        ...
    }
}

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?


回答1:


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. it makes your code quite ugly (imagine you have thousands of tests)
  2. it is less reusable
  3. less object-oriented: it is more OO to bind an object KeyStroke to an object Action (see more on Actions here)
  4. it is more error-prone because your code is less readable and can become gigantic
  5. your code is tightly coupled (you can hardly move your KeyListener in a separate class)
  6. in your test, you check which button has fired the event, but you don't know yet which key was typed. You will have to add more tests to find that out.

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.

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



来源:https://stackoverflow.com/questions/10609388/difference-between-keybindings-and-keylisteners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!