如果您可以这样做,那么 KeyBindings 的意义何在:
// 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) {
...
}
...
}
}
假设我有十个按钮。然后,如果您使用 KeyBindings,则必须为每个按钮创建单独的键绑定。我展示的例子不是更有效率吗?为什么不?