Mygame
package com.sun.c;import java.awt.event.KeyListener;import com.sun.v.MyJpanel;import com.sun.v.Myjframe;public class Mygame { public Mygame() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Myjframe jframe = new Myjframe(); MyJpanel panel = new MyJpanel(); jframe.add(panel); jframe.addKeyListener(panel); }} Myjframe
package com.sun.v;import javax.swing.JFileChooser;import javax.swing.JFrame;/* * 这里采用MVC的设计模式,讲逻辑和页面分开, */public class Myjframe extends JFrame{ public Myjframe(){ this.setTitle("myworld"); this.setVisible(true); this.setSize(400,400); this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); } }
MyJpanel
package com.sun.v;import java.awt.Graphics;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JPanel;import com.sun.m.Dog;public class MyJpanel extends JPanel implements KeyListener,Runnable{ public MyJpanel() { //MyJpanel jp = new MyJpanel(); Thread td = new Thread(this); td.start(); } Dog dog = new Dog(20,20,2); public void paint(Graphics g){ super.paint(g); g.draw3DRect(dog.x, dog.y,20 ,20, false); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub //System.out.println("sunzhiyan"); switch (e.getKeyCode()){ case KeyEvent.VK_W: dog.direct = 0; dog.move(dog.direct); break; case KeyEvent.VK_D: dog.direct = 1; dog.move(dog.direct); break; case KeyEvent.VK_S: dog.direct = 2; dog.move(dog.direct); break; case KeyEvent.VK_A: dog.direct = 3; dog.move(dog.direct); break; } this.repaint(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void run() { // TODO Auto-generated method stub while(true){ try { Thread.sleep(1000); //System.out.println("我被调用了"); dog.direct = 2; dog.move(dog.direct); this.repaint(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
Dog
1 package com.sun.m; 2 3 public class Dog { 4 public int x; 5 public int y; 6 public int direct ; 7 public Dog(int x,int y, int direct){ 8 this.x = x; 9 this.y = y;10 this.direct = direct;11 }12 public void move(int direct){13 switch (direct){ 14 case 0:15 this.y--;16 break;17 case 1:18 this.x++;19 break;20 case 2:21 this.y++;22 break;23 case 3:24 this.x--;25 break; 26 }27 28 }29 }