The difference between KeyBindings and KeyListeners

What is the point of KeyBindings if you can 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) {
            ...
        }
        ...
    }
}

Say I have ten buttons . Then, if you use KeyBindings, you will need to make a separate key binding for each button. Isn't that an example that I have shown more efficiently? Why not?

+3
source share
1 answer

If you just consider CPU cycles, yes, it is (possibly) more efficient (and after careful consideration, I’m not even sure about that). But there are several serious points against this:

  • it makes your code pretty ugly (imagine you have thousands of tests).
  • it is less reusable
  • -: OO KeyStroke Action (. )
  • , .
  • ( KeyListener )
  • , , , , . , .

, , .

, .

, KeyListener JButton. ActionListener.

+2

All Articles