日期:2014-05-20 浏览次数:20725 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Pete extends JFrame { PetePanel pete = new PetePanel(); public Pete() { super("Pixel Pete"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pane = new JPanel(); pane.setLayout(new GridLayout(1, 1, 15, 15)); pane.add(pete); this.addKeyListener(new KeyAdapter(){//没有得到焦点,放frame容易获取焦点。 @Override public void keyPressed(KeyEvent e) { System.out.println("ppppp"); if (e.getKeyCode() == KeyEvent.VK_LEFT) { pete.current = 1; pete.x =pete.x - 10; } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { pete.current = 0; pete.x = pete.x + 10; } else if (e.getKeyCode() == KeyEvent.VK_UP) { pete.current = 2; pete.y = pete.y - 10; } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { pete.current = 3; pete.y = pete.y - 10; } repaint(); } public void keyTyped(KeyEvent e){ System.out.println("kkkkk"); } public void keyReleased(KeyEvent e) { System.out.println("rrrrrr"); } }); setContentPane(pane); this.setVisible(true); this.requestFocus();//具体办法可以手设焦点。如果焦点有问题,就优先想到它 } public static void main(String[] arguments) { Pete Penguin = new Pete(); PetePanel a = new PetePanel(); } } class PetePanel extends JPanel{ // JPanel.requestFocus(); // Thread runner; Image petePics[] = new Image[4]; Image back; int current = 0; int x = 100; int y = 100; PetePanel() { super(); setBackground(Color.black); String peteSrc[] = { "right.jpg", "left.jpg", "up.jpg", "down.jpg" }; Toolkit kit = Toolkit.getDefaultToolkit(); for (int i = 0; i < petePics.length; i++) { petePics[i] = kit.getImage(peteSrc[i]); } back = kit.getImage("abc.bmp"); // if(runner==null) // { // runner=new Thread(this); // runner.start(); // } } public void paint(Graphics comp) { Graphics2D comp2D = (Graphics2D) comp; // if(back!=null) // comp2D.drawImage(back,0,0,this); comp2D.setColor(Color.black); comp2D.fillRect(0, 0, 500, 500); if (petePics[current] != null) comp2D.drawImage(petePics[current], x, y, this); } public void fun() { for (int i = 0; i < 500; i++) { x = x + 5; current = 1; repaint(); } } }