问题
Is it a good practice to add few listeners for JComponent in different part of code? Should I create one bigger listener?
For example I have JTextField, I noticed that both KeyListeners are called.
JTextField textField = new JTextField();
textField.addKeyListener(new KeyListener()
{
@Override
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
}
@Override
public void keyReleased(KeyEvent e)
{
something();
}
});
textField.addKeyListener(new KeyListener()
{
@Override
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
}
@Override
public void keyReleased(KeyEvent e)
{
somethingElse();
}
});
回答1:
Well, it's bad practice to use KeyListener
(generally, but especially) with text components.
- Is it good practice to use multiple listeners on the same component, generally yes.
- Is it good practice to use single use listeners with components, yes.
- Is it good practice to have one big listener, IMHO, no. The reasoning is, you want to create small units of work that do a single, isolated job. Sure you might be able to abstract a listener which would allow you to re-use, but having a single monolithic listener is just a maintenance nightmare
Most listener interfaces tend to have "adapter" class, which are just concrete implementations of the listener interface without any functionality, so you can pick and choose the methods you actually want to use
来源:https://stackoverflow.com/questions/34671548/two-keylisteners-on-jtextfield