16.18
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.awt.Graphics; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 public class Test_16_18 extends JFrame{ 6 private JP jp = new JP(); 7 public Test_16_18() 8 { 9 add(jp); 10 jp.setFocusable(true); //必须在JPanel这里设置focusable 11 } 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Test_16_18 frame = new Test_16_18(); 15 frame.setSize(300,300); 16 frame.setTitle("Test_16_18"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setLocationRelativeTo(null); // Center the frame 19 frame.setVisible(true); 20 } 21 22 static class JP extends JPanel{ 23 private int x = 140, y = 140; 24 public JP(){ 25 addKeyListener(new KeyAdapter(){ 26 public void keyPressed(KeyEvent e){ 27 switch(e.getKeyCode()){ 28 case KeyEvent.VK_UP: y -= 10; break; 29 case KeyEvent.VK_DOWN: y += 10; break; 30 case KeyEvent.VK_LEFT: x -= 10; break; 31 case KeyEvent.VK_RIGHT: x += 10; break; 32 }repaint(); 33 } 34 }); 35 } 36 protected void paintComponent(Graphics g){ 37 super.paintComponent(g); 38 g.drawOval(x, y, 30, 30); 39 } 40 } 41 }
需要注意的是,必须给JPanel设置焦点,否则键盘无用。