sinat_26083883
sinat_26083883
2017-10-29 08:38

java frame 添加 方向键监听问题

  • java
  • 监听
  • eclipse
  • frame
 package Demo;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;

import javax.swing.ImageIcon;

public class Demo  {
    frame f = null;
    public Demo(){
        f = new frame();
        Canvas c = new Canvas();
        Panel p = new Panel();
        f.setLayout(null);
        p.setLayout(null);
        f.setSize(600, 600);
        c.setSize(600, 600);

        f.add(p);
        p.add(c);
        f.requestFocus();
        f.addKeyListener(f);
        f.setBackground(Color.black);
        f.setVisible(true);
    }
    public static void main(String[] args)
    {
        Demo d = new Demo();
    }
}
class frame extends Frame implements KeyListener{
    private Image img = null;
    private int x =50;
    private int y = 50;
    private ImageIcon ii = new ImageIcon("D:\\Eclipse\\WORKPLACE\\image\\ccr.jpg");
    public frame(){
        super();
    }
    /*public void Frame(){
        frame f = new frame();
        Panel p = new Panel();
        Canvas c = new Canvas();
        f.setSize(300, 300);
        f.add(p);
        p.setSize(300, 300);
        p.add(c);
        c.setSize(300, 300);
        f.setVisible(true);
    }*/
    @Override
    public void paint(Graphics g)
    {
         super.paint(g);  

        img = ii.getImage();
        g.drawImage(img, x, y,15,15, this);
    }
    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
        int z;
        switch(e.getKeyCode())  
        {  
            case KeyEvent.VK_UP:  
                y-=7;  
                //调用repaint()函数,重新绘制小球位置  
               // z=1;
                this.repaint();  
                break;  
            case KeyEvent.VK_DOWN:  
                y+=7;  
                //调用repaint()函数,重新绘制小球位置  
                //z=2;
                this.repaint();  
                break;  
            case KeyEvent.VK_LEFT:  
                x-=7;  
                //调用repaint()函数,重新绘制小球位置  
               // z=3;
                this.repaint();  
                break;  
            case KeyEvent.VK_RIGHT:  
                x+=7;  
                //调用repaint()函数,重新绘制小球位置  
                //z=4;
                this.repaint();  
                break;  
        }  
    }
    @Override
    public void keyPressed(KeyEvent e) {


    }
    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答