When programming graphical interfaces in Java using swing
, we are always faced with both types, mainly to assign and create events from button actions or other components.
Although I've been working with swing
for some time, I've always been curious about the difference between listeners and adapters, and how they are replaced in some cases like the example below:
Keyboard event in a
JTextField
withAdapter
:
jTextField1.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
}
});
Keyboard event in a
JTextField
withListener
:
jTextField1.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void keyPressed(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
The interface listener forces you to implement some methods, and the adapter only those needed.
Based on this, what differences (if any) between Listeners
and Adapters
within the swing API? How do I know when it's more advantageous to use one or the other?