Two KeyListeners on JTextField

我的未来我决定 提交于 2020-01-17 01:29:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!