我正在使用Java中的keyListener创建一个Sprite Mover

时间:2015-11-02 15:37:29

标签: java swing jlabel keylistener

我正在研究一个精灵推动者,但它似乎不起作用,任何人都可以看看并告诉我什么是错的?它应该通过KeyListener工作,以便用箭头键移动精灵,但是,我的移动功能只能向上移动,而不是其他方向,请帮助。

package moving.sprite;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;


/**
 *
 * @author c
 */

public class MovingSprite implements KeyListener,
        ActionListener{

    /**
     * @param args the command line arguments
     * 
     */

    // Make a sprite movable around the window by using the arrow keys

    // Data : Used for paths for the File object

    // Stills

    private static String fstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Front.png";
    private static String bstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Back.png";
    private static String lstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Left.png";
    private static String rstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Right.png";

    //

    // Walking

    private static String fwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Front.png";
    private static String bwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Back.png";
    private static String lwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Left.png";
    private static String rwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Right.png";

    //

    // Movement position

    private static int moved = 0;
    private static int xa = 0;
    private static int ya = 0;
    private static String j;
    private static String direction;

    // 0 = front
    // 1 = back
    // 2 = left
    // 3 = right

    //

    // Gui Constructors

    private static JFrame mainframe;
    private static Container contentPane;
    private static SpringLayout layout;
    private static Component frame;
    private static BufferedImage img;
    private static ImageIcon iconb;
    private static JLabel lab;
    private static JFrame mainframeb;
    private static JButton upb;
    private static JButton downb;
    private static JButton leftb;
    private static JButton rightb;

    public static void main(String[] args) {

        runthis();


    }

    private static void messagep ( String message ) {

        JOptionPane.showMessageDialog(frame,
    message);

    }

    private static void changesprite(String pos) {

        j = pos;

        img = null;

        try {

        img = ImageIO.read(new File(j));

        } catch (IOException e) {

        }

        iconb = new ImageIcon(img, "Sprite");

        lab.setIcon(iconb);

    }

    private static void reset() {

        xa = 0;
        ya = 0;
        lab.setLocation(xa, ya);
        System.out.println("Reset!");

    }

    private static void move() {

        lab.setLocation(xa, ya);

        if ( moved == 1 ) {

            // Down, works

            changesprite(fstill);
            ya = (lab.getLocationOnScreen().y);
            xa = (lab.getLocationOnScreen().x*2*(-(1)));
            lab.setLocation(xa, ya);
            System.out.println("Down : (" + xa + " , " + ya +  " ) ");

        }

        if ( moved == 0 ) {

            // Backwards, 

            changesprite(bstill);
            ya = (lab.getLocationOnScreen().y)-2;
            xa = (lab.getLocationOnScreen().x);
            lab.setLocation(xa, ya);
            System.out.println("Up : (" + xa + " , " + ya +  " ) ");

        }

        if ( moved == 2 ) {

            changesprite(lstill);

        }

        if ( moved == 3 ) {

            changesprite(rstill);

        }

        lab.setLocation(xa, ya);

    }

    private static void runthis() {

        messagep("Disclaimer : Sprite's are originally by Nintendo, sprites were ripped by : Silentninja.");
        messagep("Program made by : c");

        mainframe = new JFrame("Fire Red Sprite");
        mainframe.setSize(100, 100);

        contentPane = mainframe.getContentPane();
        layout = new SpringLayout();


        j = fstill;

        img = null;

        try {

        img = ImageIO.read(new File(j));

        } catch (IOException e) {

        }

        iconb = new ImageIcon(img, "Sprite");

        lab = new JLabel(iconb);

        mainframe.add(lab);
        lab.setLocation(100, 100);

        mainframeb = new JFrame("Fire Red Moving");
        mainframeb.setSize(300, 70);

        upb = new JButton("Up");
        downb = new JButton("Down");
        leftb = new JButton("Left");
        rightb = new JButton("Right");

        upb.setSize(50, 50);
        downb.setSize(50, 50);
        leftb.setSize(50, 50);
        rightb.setSize(50, 50);

        mainframeb.add(upb);
        mainframeb.add(downb);
        mainframeb.add(leftb);
        mainframeb.add(rightb);

        contentPane.setLayout(layout);
        mainframe.pack();
        mainframe.setVisible(true);
        mainframeb.setLayout(new FlowLayout (FlowLayout.LEADING));
        mainframeb.setVisible(true);


        reset();

    }

    private static void directionassign() {

        if ( moved == 2 ) {

            direction = "LEFT";

        }

        if ( moved == 3 ) {

            direction = "RIGHT";

        }

        if ( moved == 1 ) {

            direction = "UP";

        }

        if ( moved == 0 ) {

            direction = "DOWN";

        }

    }

    @Override
    public void keyTyped(KeyEvent ke) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent ke) {

        if(ke.getKeyCode()  == KeyEvent.VK_LEFT) moved = 2;
        else if(ke.getKeyCode()  == KeyEvent.VK_RIGHT) moved = 3;
        else if(ke.getKeyCode()  == KeyEvent.VK_UP) moved = 1;
        else if(ke.getKeyCode()  == KeyEvent.VK_DOWN) moved = 0;

        move();
        directionassign();
        System.out.println(moved + " " + direction);

    }

    @Override
    public void keyReleased(KeyEvent ke) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        move();
    }

    private void displayInfo(KeyEvent e, String keyStatus){

        int id = e.getID();
        if (id == KeyEvent.KEY_PRESSED) {

            char c = e.getKeyChar();
            System.out.println(c);

        }

    }

}/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package moving.sprite;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;


/**
 *
 * @author c
 */

public class MovingSprite implements KeyListener,
        ActionListener{

    /**
     * @param args the command line arguments
     * 
     */

    // Make a sprite movable around the window by using the arrow keys

    // Data : Used for paths for the File object

    // Stills

    private static String fstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Front.png";
    private static String bstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Back.png";
    private static String lstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Left.png";
    private static String rstill = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Stills\\Right.png";

    //

    // Walking

    private static String fwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Front.png";
    private static String bwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Back.png";
    private static String lwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Left.png";
    private static String rwalk = "C:\\Users\\c\\Documents\\NetBeansProjects\\Moving Sprite\\src\\Sprite Images\\Walking\\Right.png";

    //

    // Movement position

    private static int moved = 0;
    private static int xa = 0;
    private static int ya = 0;
    private static String j;
    private static String direction;

    // 0 = front
    // 1 = back
    // 2 = left
    // 3 = right

    //

    // Gui Constructors

    private static JFrame mainframe;
    private static Container contentPane;
    private static SpringLayout layout;
    private static Component frame;
    private static BufferedImage img;
    private static ImageIcon iconb;
    private static JLabel lab;
    private static JFrame mainframeb;
    private static JButton upb;
    private static JButton downb;
    private static JButton leftb;
    private static JButton rightb;

    public static void main(String[] args) {

        runthis();


    }

    private static void messagep ( String message ) {

        JOptionPane.showMessageDialog(frame,
    message);

    }

    private static void changesprite(String pos) {

        j = pos;

        img = null;

        try {

        img = ImageIO.read(new File(j));

        } catch (IOException e) {

        }

        iconb = new ImageIcon(img, "Sprite");

        lab.setIcon(iconb);

    }

    private static void reset() {

        xa = 0;
        ya = 0;
        lab.setLocation(xa, ya);
        System.out.println("Reset!");

    }

    private static void move() {

        lab.setLocation(xa, ya);

        if ( moved == 1 ) {

            // Down, works

            changesprite(fstill);
            ya = (lab.getLocationOnScreen().y);
            xa = (lab.getLocationOnScreen().x*2*(-(1)));
            lab.setLocation(xa, ya);
            System.out.println("Down : (" + xa + " , " + ya +  " ) ");

        }

        if ( moved == 0 ) {

            // Backwards, 

            changesprite(bstill);
            ya = (lab.getLocationOnScreen().y)-2;
            xa = (lab.getLocationOnScreen().x);
            lab.setLocation(xa, ya);
            System.out.println("Up : (" + xa + " , " + ya +  " ) ");

        }

        if ( moved == 2 ) {

            changesprite(lstill);

        }

        if ( moved == 3 ) {

            changesprite(rstill);

        }

        lab.setLocation(xa, ya);

    }

    private static void runthis() {

        messagep("Disclaimer : Sprite's are originally by Nintendo, sprites were ripped by : Silentninja.");
        messagep("Program made by : c");

        mainframe = new JFrame("Fire Red Sprite");
        mainframe.setSize(100, 100);

        contentPane = mainframe.getContentPane();
        layout = new SpringLayout();


        j = fstill;

        img = null;

        try {

        img = ImageIO.read(new File(j));

        } catch (IOException e) {

        }

        iconb = new ImageIcon(img, "Sprite");

        lab = new JLabel(iconb);

        mainframe.add(lab);
        lab.setLocation(100, 100);

        mainframeb = new JFrame("Fire Red Moving");
        mainframeb.setSize(300, 70);

        upb = new JButton("Up");
        downb = new JButton("Down");
        leftb = new JButton("Left");
        rightb = new JButton("Right");

        upb.setSize(50, 50);
        downb.setSize(50, 50);
        leftb.setSize(50, 50);
        rightb.setSize(50, 50);

        mainframeb.add(upb);
        mainframeb.add(downb);
        mainframeb.add(leftb);
        mainframeb.add(rightb);

        contentPane.setLayout(layout);
        mainframe.pack();
        mainframe.setVisible(true);
        mainframeb.setLayout(new FlowLayout (FlowLayout.LEADING));
        mainframeb.setVisible(true);


        reset();

    }

    private static void directionassign() {

        if ( moved == 2 ) {

            direction = "LEFT";

        }

        if ( moved == 3 ) {

            direction = "RIGHT";

        }

        if ( moved == 1 ) {

            direction = "UP";

        }

        if ( moved == 0 ) {

            direction = "DOWN";

        }

    }

    @Override
    public void keyTyped(KeyEvent ke) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent ke) {

        if(ke.getKeyCode()  == KeyEvent.VK_LEFT) moved = 2;
        else if(ke.getKeyCode()  == KeyEvent.VK_RIGHT) moved = 3;
        else if(ke.getKeyCode()  == KeyEvent.VK_UP) moved = 1;
        else if(ke.getKeyCode()  == KeyEvent.VK_DOWN) moved = 0;

        move();
        directionassign();
        System.out.println(moved + " " + direction);

    }

    @Override
    public void keyReleased(KeyEvent ke) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        move();
    }

    private void displayInfo(KeyEvent e, String keyStatus){

        int id = e.getID();
        if (id == KeyEvent.KEY_PRESSED) {

            char c = e.getKeyChar();
            System.out.println(c);

        }

    }

}

1 个答案:

答案 0 :(得分:3)

if ( moved == 1 )

不要使用“魔术数字”。没有人知道“1”意味着什么,并且很容易在代码中的其他地方输入错误,你可能需要引用该变量。

private static JFrame mainframe;
private static Container contentPane;
private static SpringLayout layout;
private static Component frame;

private static void messagep ( String message ) {

摆脱所有静态变量的方法。这不是设计应用程序的正确方法。

结帐Motion Using the Keyboard。它解释了使用KeyListener的常见问题,并提出了一种更好的方法,即使用Key Bindings。提供了工作实例。