-
public class MyPanel extends JFrame {
private Panel panel= new Panel();
public MyPanel(){
super();
this.setBounds(300, 200, 450, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(panel);
this.add(panel );
this.setVisible(true);
}
}
class Panel extends JPanel implements KeyListener{
private Hero hero;
@Override
public void paint(Graphics g) {
super.paint(g);
g.fillRect(0, 0, 450, 500);
//画x英雄坦克
hero=new Hero(50, 100, 0);
System.out.println(hero);
drawTanke(hero, g);
}
public void drawTanke(Hero t,Graphics g) {
switch (t.getFangxiang()) {
case 0: {
g.setColor(Color.YELLOW);
g.fill3DRect(t.getX(), t.getY(), 10, 60, false);
g.fill3DRect(t.getX()+30, t.getY(), 10, 60, false);
g.fill3DRect(t.getX()+10, t.getY()+18, 20, 25, false);
g.fillOval(t.getX()+10, t.getY()+18, 20,25);
g.fill3DRect(t.getX()+18, t.getY(), 5, 21, false);
}
default:
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("按下了" +e.getKeyCode());
if (e.getKeyCode()==38 && hero !=null) {
System.out.println(hero);
int y = hero.getY();
System.out.println(y);
y =--y;
System.out.println(y);
hero.setY(y);
}
repaint();
}
输出结果
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
按下了38
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
100
99
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
按下了38
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
100
99
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
按下了38
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
100
99
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
按下了38
Hero [getX()=50, getY()=100, isLive()=true, getFangxiang()=0]
100
99