Anonymous181
Anonymous181

Reputation: 1873

Difference between KeyBindings and 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) {
            ...
        }
        ...
    }
}

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?

Upvotes: 3

Views: 480

Answers (1)

Guillaume Polet
Guillaume Polet

Reputation: 47608

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.

Upvotes: 2

Related Questions