1 PackageCom.java7.keyboardcontrolmyball.main;2 Importjava.awt.*;3 Importjava.awt.event.*;4 5 Public classKeyboardcontrolmyball {6 Public Static voidMain (string[] args) {7Frame W =NewFrame ();8W.setsize (300,400);9 TenMypanel MP =NewMypanel (); One W.add (MP); A - W.addkeylistener (MP); - Mp.addkeylistener (MP); the - w.show (); - } - } + - classMypanelextendsPanelImplementsKeyListener { + intx = 30; A inty = 30; at Public voidPaint (Graphics g) { -G.filloval (x, Y, 20, 20); - } - - @Override - Public voidkeypressed (KeyEvent arg0) { in if(Arg0.getkeycode () = = 37) { -x--; to } + if(Arg0.getkeycode () = = 38) { -y--; the } * if(Arg0.getkeycode () = = 39) { $X + +;Panax Notoginseng } - if(Arg0.getkeycode () = = 40) { they++; + } A //System.out.println (Arg0.getkeycode ()); the repaint (); + } - @Override $ Public voidkeyreleased (KeyEvent e) { $ } - @Override - Public voidkeytyped (KeyEvent e) { the - }Wuyi}
Exercises. Keyboard control Ball