我的KeyPressed不能用Java工作

时间:2016-08-14 23:38:42

标签: java user-interface keylistener

我在java中创建一个游戏只是为了我自己的享受,当我按下移动键时,我选择了我在屏幕上的矩形不动。这是我的第一堂课

package Game;
import java.awt.*;
import javax.swing.*;
import Game.Player;

public class Frame {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        Player pl = new Player();

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.setSize(600, 600);
        f.setTitle("Filler");
        f.add(pl);

        f.setVisible(true);

    }

}

我的第二堂课

package Game;

import java.awt.*;
import java.awt.event.*;


import javax.swing.*;

public class Player extends JPanel implements ActionListener, KeyListener {

    Timer t = new Timer(5,this);
    double x = 0, y = 0, velx = 0, vely = 0;

    public Player(){
        t.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    public void paintComponent (Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.RED);
        g2.fillRect(40, 40, 20, 30);
    }
    @Override
    public void keyReleased(KeyEvent e) {
        velx = 0;
        vely = 0;

    }
    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        x += velx;
        y += vely;
        repaint();

    }



    @Override
    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_D){
            velx = 1.5;
            vely = 0;
        }
        else if(e.getKeyCode() == KeyEvent.VK_A){
            velx = -1.5;
            vely = 0;
        }
        else if(e.getKeyCode() == KeyEvent.VK_W){
            vely = -1.5;
            velx = 0;
        }


    }

}

我稍后会添加更多课程,但这就是我现在所拥有的课程。有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

这与KeyListener无关,无论xy是什么,都是绘制矩形的事实。如果用变量xy替换矩形的x和y值,它可以正常工作。

public void paintComponent (Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.RED);
    g2.fillRect((int)x, (int)y, 20, 30); // change line here
}