Difference between KeyBindings and KeyListeners

后端 未结 1 1870
灰色年华
灰色年华 2021-01-20 03:55

What is the point of KeyBindings if you could just do:

// Imports

public void Test {
    JButton button1;
    JButton button2;
    JButton button3;
    ...
         


        
相关标签:
1条回答
  • 2021-01-20 04:20

    If your are purely counting CPU-cycles, yes it is (arguably) more efficient (and after careful consideration, I am not even sure of that). But there are some strong points against it:

    1. it makes your code quite ugly (imagine you have thousands of tests)
    2. it is less reusable
    3. less object-oriented: it is more OO to bind an object KeyStroke to an object Action (see more on Actions here)
    4. it is more error-prone because your code is less readable and can become gigantic
    5. your code is tightly coupled (you can hardly move your KeyListener in a separate class)
    6. in your test, you check which button has fired the event, but you don't know yet which key was typed. You will have to add more tests to find that out.

    So for very localized problems, your approach can be sufficient, while for a bigger view, it cannot hold.

    You can find in the third paragraph here, some similar and additional comments on this matter.

    Finally, it is a bit weird to put a KeyListener on a JButton. Usually, we register an ActionListener.

    0 讨论(0)
提交回复
热议问题