user5746456
user5746456

Reputation:

Two KeyListeners on JTextField

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();
     }
  });

Upvotes: 0

Views: 119

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

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

Upvotes: 3

Related Questions