1 package PartOfConstruct; 2 import java.awt.Graphics; 3 import java.awt.event.KeyAdapter; 4 import java.awt.event.KeyEvent; 5 import java.awt.image.BufferedImage; 6 import java.io.IOException; 7 import java.util.Timer; 8 import java.util.TimerTask; 9 import javax.imageio.ImageIO; 10 import javax.swing.JFrame; 11 import javax.swing.JPanel; 12 public class partOne extends JPanel{ 13 public static BufferedImage bg; 14 static{ 15 try { 16 bg =ImageIO.read(partOne.class.getResource("bg.png")); 17 } catch (IOException e) { 18 // 加载图片的异常处理 19 e.printStackTrace(); 20 } 21 } 22 int x=5,y=5; 23 public void paint(Graphics g) { 24 g.drawImage(bg, 0,0, null); 25 g.fillOval(x, y, 20, 20); 26 x+=5; 27 y+=5; 28 } 29 public void moving(){ 30 this.addKeyListener(new KeyAdapter() { 31 public void keyPressed(KeyEvent e) { 32 System.out.println("按下"+e.getKeyCode()); 33 } 34 35 public void keyReleased(KeyEvent e) { 36 System.out.println("弹起"+e.getKeyCode()); 37 } 38 }); 39 } 40 public void Ationn(){ 41 Timer timer = new Timer(); 42 timer.scheduleAtFixedRate(new TimerTask() { 43 public void run() { 44 moving(); 45 repaint(); 46 } 47 }, 100, 1000); 48 } 49 public static void main(String[] args) { 50 JFrame jj = new JFrame(); 51 partOne pp = new partOne(); 52 jj.setVisible(true); 53 jj.setSize(500, 500); 54 jj.setResizable(false);//锁定窗口的大小不可随意拉动 55 jj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口 56 jj.setLocation(200, 50); 57 jj.add(pp); 58 pp.Ationn(); 59 pp.moving(); 60 } 62 }
为什么无法在控制台输出我按下的键码?