I have a JFrame
and I want to add a KeyListener
to it, because I want to close it by typing alt + F11 (I know, you can just click the cross in the upper right corner, but there is a reason why I need a shortcut).
So I added a KeyListener
:
addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_F11 && event.isAltDown()) {
dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
});
As you can see, I only need the keyPressed()
method. But if I remove keyReleased()
and keyTyped()
, I get this error:
The type new KeyListener(){} must implement the inherited abstract method KeyListener.keyReleased(KeyEvent)
Is there a way around it, or do I really have to add these unused methods?
Thanks in advance!
KeyListener
is an interface. If you want to implement an interface, you need to implement all of its methods (as interface doesn't provide a body to all of its methods). If you take a look atKeyListener
interface in Java API documentation, you can see that it has 3 methods that need to be implemented:One of the solutions for you to avoid implementing all of the methods is to use a
KeyAdapter
class (fromjava.awt.event
package). As Java documentation states:The methods in this class are empty. This class exists as convenience for creating listener objects. Extend this class to create a KeyEvent listener and override the methods for the events of interest. (If you implement the KeyListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about.)
So, you could modify your
addKeyListener
method to something like this:Because this is what
keyListener
function is. It needs to include all of these functions. You may just use this;You need all of the key events for key listener because it is just required for the program to compile correctly in Java. If you do not need them just keep those methods blank.