How to detect a key press in Java

前端 未结 6 1631
野的像风
野的像风 2020-12-30 07:29

My son (aged 11) who is learning Java is going to enter a question and some code. He tells me he has not been able to find the answer to this question on the site. You will

6条回答
  •  执笔经年
    2020-12-30 08:32

    So GUI are event driven. Everything that occurs is driven by an event. A key press is an event. A component needs to listen for events, and do something when the event is fired. You can read more about how to write different listeners here. Some of the basic listeners are fairly easy to recognize (by name) like KeyListener or MouseListener. ActionListener is also pretty common for button presses. You'll want to go through the tutorials and learn the different listeners.

    Note though that with Swing there are focus issues with using a KeyListener so it is preferred to use key bindings. As stated in the KeyListener tutorial:

    To define special reactions to particular keys, use key bindings instead of a key listener

    A tutorial for key bindings can be found here and an example can been seen here. Here's the gif from the example, showing the movement of rectangle with a key press using key bindings

    enter image description here


    UPDATE just notice.

    1. Don't override the paint method of JPanel
    2. Never call repaint() from inside a paint/paintComponent method

      public void paint() {//This is where the graphic is painted to the screen
          repaint();
      }
      

    Get completely rid of the above code.

提交回复
热议问题