7
When programming java graphical interfaces using swing
, we always come across both types, mainly to assign and create events from button actions or other components.
Though I’ve been messing around with swing
, I’ve always been curious about the difference between listeners and Adapters, and how they replace themselves 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 Listener interface requires implementing some methods, and Adapter only the necessary ones.
Based on this, what differences (if any) between Listeners
and Adapters
within the swing API? How to know when it is most advantageous to use one or the other?
Who implements whom? It was not very clear, and as the question was more specific of the swing Adapters. if possible, I would like the answer to be more focused on them.
– user28595
Hi @Diegof, added an example. I hope it helps.
– josivan
The answer is already complete, but it would be interesting for you to add the translation of the citation in English, for users who do not know the English language, to have a good understanding.
– user28595
I added the translation. I think it will help. Greetings.
– josivan