Reputation: 1873
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
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:
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