I'm practicing with events and wanted to set it up so I had a class that responded to both button and key presses, it compiles fine, but the key events aren't calling the method/working at all.
This is the class:
class CircleListener extends KeyAdapter implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nlrg_button) canvas.enlarge();
else if (e.getSource() == shrink_button) canvas.shrink();
else if (e.getSource() == superenlarger_button) canvas.enlargeAlot();
else if (e.getSource() == supershrinker_button) canvas.shrinkAlot();
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_DOWN: canvas.circleDown(); break;
case KeyEvent.VK_UP: canvas.circleUp(); break;
case KeyEvent.VK_LEFT: canvas.circleLeft(); break;
case KeyEvent.VK_RIGHT: canvas.circleRight(); break;
}
repaint();
}
}
this is the instantiation + registration:
CircleListener listener = new CircleListener();
// Bind buttons with respective eventlistener class
nlrg_button.addActionListener(listener);
shrink_button.addActionListener(listener);
superenlarger_button.addActionListener(listener);
supershrinker_button.addActionListener(listener);
// Bind canvas to keylistener class
canvas.addKeyListener(listener);
The methods they attempt to call exist and work as intended, I assured as such by calling them with the buttons before asking.
Why is it not working/what am I missing? & Is there a more efficient form?
Why is it not working/what am I missing?
KeyEvents are only dispatched to the component that has focus. Since you have many components on your panel the panel will never have focus. You should NOT be using KeyEvents for this.
I had a class that responded to both button and key presses
That is a good design, however you should NOT be using KeyEvents for this. Instead you should be using Key Bindings
.
When you use Key Bindings you can share the Action between both the button and a KeyStroke. Read the section from the Swing tutorial on How to Use Key Bindings for more information and examples.
Building you application using Actions is a good design. The tutorial also has a section on How to Use Action
that you should look at. All Swing components use Actions and Key Bindings. You can check out Key Bindings for the default bindings for Swing components as well as some example code for using key bindings.