请求大佬支援!!!这个键盘监听事件怎么加上去
package game;

import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Window extends JFrame implements Runnable{
    static int x1 = 0;//蛇头横坐标
    static int y1 = 25;//蛇头纵坐标
    Button b[] = new Button[50];//蛇数组
    Button fruit = new Button();//水果
    boolean flag = true;// 判断是否吃到果实
    int x, y;// 水果坐标
    Move move = null;

    public Window() {

        b[0] = new Button();// 蛇头
        b[0].setBounds(x1, y1, 10, 10);
        b[0].setBackground(Color.blue);
        add(b[0]);

        for (int i = 1; i < 50; i++) {
            b[i] = new Button();// 蛇长度
        }

        if (flag) {// 水果的随机位置
            while (flag) {
                x = (int) (1 + Math.random() * 1175);
                y = (int) (1 + Math.random() * 800);
                System.out.println("x-->" + x);
                System.out.println("y-->" + y);
                fruit.setBounds(x, y, 10, 10);
                fruit.setBackground(Color.yellow);
                add(fruit);
                flag = false;
            }
        }

        this.addKeyListener(move);

        setLayout(null);
        setTitle("Retro Snaker");
        setSize(1200, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void run() {
        while(true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            x1+=5;
            b[0].setBounds(x1, y1, 10, 10);
        }
    }
}

class Move extends Window implements KeyListener {

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {// 上
                y1 += 5;
                System.out.println("上");
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {// 下
                y1 -= 5;
                System.out.println("下");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {// 左
            x1 -= 5;
            System.out.println("左");
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {// 右
            x1 += 5;
            System.out.println("右");
        }
        this.repaint();
    }

    public void keyReleased(KeyEvent e) {

    }
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐