码迷,mamicode.com
首页 > 其他好文 > 详细

16.18

时间:2016-07-10 13:56:37      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享
 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 }
Test_16_18.java

需要注意的是,必须给JPanel设置焦点,否则键盘无用。

技术分享

 

16.18

标签:

原文地址:http://www.cnblogs.com/wanjiang/p/5657552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!