用Java移动对象(KeyPressed)

时间:2017-04-15 15:53:17

标签: java keypress keylistener

对于我在学校的项目,我们必须制作游戏。

我正在尝试使用箭头键移动对象,但如果我运行它并按下其中一个键,则没有任何反应。

我是否可以在错误的位置实施addKeyListener(this);

package VoorbeeldSpel;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;


import javax.swing.*;

public class PlayPanel extends JPanel implements ActionListener, KeyListener {

    private static final long serialVersionUID = 584263623777101573 L;
    final static String IMAGE_FOLDER = "images/";
    final static String FILE_FOLDER = "files/";

    private Timer spelTimer = new Timer(50, this); // elke 1000 milliseconden zal een event gelanceerd worden

    private JButton menuKnop;
    private MijnProject mainVenster;


    MusicPlayer music;
    private Image ninjaImage;
    private Image BackgroundImage;

    public int pos_x, pos_y;
    public int v_x, v_y;

    private String inputText = "";

    public PlayPanel(MijnProject mainVenster) {
        this.mainVenster = mainVenster;

        menuKnop = new JButton("Menu");
        menuKnop.addActionListener(this);

        this.add(new JLabel("We are playing ... "));
        this.add(menuKnop);


        addKeyListener(this);

        // Music player laden
        music = new MusicPlayer("nyancat-loop.wav", true);


        // Prentjes laden
        ninjaImage = new ImageIcon(getClass().getResource(IMAGE_FOLDER + "ninja.png")).getImage();
        BackgroundImage = new ImageIcon(getClass().getResource(IMAGE_FOLDER + "Backgroundmenu.jpg")).getImage();

        spelTimer.start(); // hier starten we de gameloop
    }

    // we gaan init aanroepen nadat we dit JPanel aan het frame hebben toegevoegd
    // op dit moment zijn de hoogte en breedte van het panel bepaald en kunnen we de pos_x en pos_y variabelen initialiseren als het midden van het scherm
    public void init() {
        addKeyListener(this);
        v_x = ;
        v_y = 0;
        pos_x = getWidth() / 2;
        pos_y = getHeight() / 2;
        addKeyListener(this);
    }
    public void gameloop() {

        pos_x += v_x;
        pos_y += v_y;
        repaint();

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(BackgroundImage, this.getWidth() / 50, this.getHeight() / 50, mainVenster.getWidth(), mainVenster.getHeight(), this);
        g.drawImage(ninjaImage, pos_x, pos_y, 60, 60, this);

        g.drawChars(inputText.toCharArray(), 0, inputText.length(), 25, getHeight() / 2);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == menuKnop) {
            mainVenster.switchPanel();
            music.stop();
            spelTimer.stop(); // stoppen van het spel

        } else if (ae.getSource() == spelTimer) {

            gameloop();
            addKeyListener(this);
            System.out.println("De volgende stap van het spel wordt uitgevoerd...");
        }
    }

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

    }

    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                v_x = 0;
                v_y = -5;
            case KeyEvent.VK_DOWN:
                v_x = 0;
                v_y = 5;
            case KeyEvent.VK_RIGHT:
                v_x = 5;
                v_y = 0;
            case KeyEvent.VK_LEFT:
                v_x = -5;
                v_y = 0;
        }

        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int Keycode = e.getKeyCode();
        switch (Keycode) {
            case KeyEvent.VK_UP:
                v_x = 0;
                v_y = 0;
            case KeyEvent.VK_DOWN:
                v_x = 0;
                v_y = 0;
            case KeyEvent.VK_RIGHT:
                v_x = 0;
                v_y = 0;
            case KeyEvent.VK_LEFT:
                v_x = 0;
                v_y = 0;
        }
        repaint();
    }
}

1 个答案:

答案 0 :(得分:1)

这可能是因为KeyListener仅在关注组件时才会收到KeyEvent。有一些建议here可能会为您解决问题;但是我不推荐他们,因为他们很笨拙。我在那里看不到的另一个kludgy解决方案是将关键监听器添加到JFrame,然后在可能会将焦点移走的任何组件上使用setFocusable(false)setFocusTraversalKeysEnabled(false)。如果您要将JButtonJTextField等其他组件添加到您的用户界面,那么关键的监听器尤其棘手。

更好的解决方案是使用Swing键绑定,这些绑定在处理焦点系统时没有问题。 Here's Q& A解释了他们的一些动机,并且tutorial here。{{3}}。您可以使用WHEN_IN_FOCUSED_WINDOW标志来保证无论哪个组件具有焦点,都会触发键绑定。