Computer questions (Elementary)-Example code of the keyboard control ball (Java)
The following code monitors the keyboard and listens to the top, bottom, and left buttons to move the ball up and down:
Import java. awt. color; import java. awt. frame; import java. awt. graphics; import java. awt. panel; import java. awt. event. keyEvent; import java. awt. event. keyListener; public class KeyListenerDemo {public static void main (String [] args) {Frame frame = new Frame (); frame. setSize (800,800); frame. setBackground (Color. BLACK); MyPanel myPanel = new MyPanel (); frame. add (myPanel); frame. addKeyListener (myPanel); myPanel. add KeyListener (myPanel); frame. show () ;}} class MyPanel extends Panel implements KeyListener {int x = 150; int y = 150; @ Overridepublic void paint (Graphics g) {g. setColor (Color. WHITE); g. fillOval (x, y, 20, 20) ;}@ Overridepublic void keyPressed (KeyEvent e) {if (e. getKeyCode () = 37) {x --;} else if (e. getKeyCode () = 38) {y-= 10;} else if (e. getKeyCode () = 39) {x + = 10;} else if (e. getKeyCode () = 40) {y + = 10;} repaint (); // do not forget !!!!!} @ Overridepublic void keyReleased (KeyEvent e) {// release the keyboard and return to the start point x = 150; y = 150; repaint () ;}@ Overridepublic void keyTyped (KeyEvent e) {// TODO Auto-generated method stub }}
When the keyboard is released, the ball returns to the starting point and runs the example as follows: