keyPressed方法无法正常工作

时间:2016-01-11 09:41:37

标签: java jframe jpanel keypress keyevent

您好我是Java的新手,我正在尝试使用箭头键在JFrame上移动JPanel(播放器)但由于某种原因它无法正常工作。我相信这是因为当按下某个键时,keyPressed方法没有响应,但我真的不知道。

这是Player类的代码:

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class Player extends JPanel implements KeyListener{
    int x=0,y=0;
    public Player(){
        this.setBounds(x, y, 9, 9);
        this.setOpaque(true);
        this.setBackground(Color.red);
        this.setFocusable(true);
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_UP){
            this.setBounds(x, x-9, 9, 9);
        }else if(key == KeyEvent.VK_DOWN){
            this.setBounds(x, y+9, 9, 9);
        }else if(key == KeyEvent.VK_RIGHT){
            this.setBounds(x+9, y, 9, 9);
        }else if(key == KeyEvent.VK_LEFT){
            this.setBounds(x-9, y, 9, 9);
        }

    }
    public void keyReleased(KeyEvent arg0) {}

    public void keyTyped(KeyEvent arg0) {}


}

提前致谢!

编辑: 这是JFrame的代码: import javax.swing.JFrame;

public class Cave {


    public static void main(String[] args) {
        JFrame frame = new JFrame("Cave Generator");
        frame.setBounds(0, 0, 0, 0);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

            Player p = new Player();
        frame.getContentPane().add(p);

    }

}

1 个答案:

答案 0 :(得分:4)

您的代码存在两个问题。

  1. 第一个问题是,一旦你在框架上调用可见调用,就会在框架上添加播放器组件。
  2. 您没有存储播放器的最后位置。
  3. 在代码中进行以下更改,它应该运行:

    <强>洞

    // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int intJour;
        int intMois;
        int intAnnee;
    
        do {
            System.out.println("Year of birth :");
            intJour = sc.nextInt();
            sc.nextLine();
        } while (intJour < 0 || intJour > 31);
    
        do {
            System.out.println("Month of birth :");
            intMois = sc.nextInt();
            sc.nextLine();
        } while (intMois < 0 || intMois > 12);
    
        do {
            System.out.println("Year of birth :");
            intAnnee = sc.nextInt();
            sc.nextLine();
        } while (intAnnee < 0 || intAnnee > Calendar.getInstance().get(Calendar.YEAR));
    
        System.out.println("Birth date: " + intJour + "-" + intMois + "-" + intAnnee);
    

    <强>播放器的keyPressed

    public class Cave {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame("Cave Generator");
            frame.setBounds(0, 0, 0, 0);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            Player p = new Player();
            frame.getContentPane().add(p);
            frame.setVisible(true);
        }
    
    }