0
我正在製作一款諾基亞蛇遊戲。我已經制作了框架和所有內容,並且已經寫好了我的算法。目前我正在做一些事情,以便我可以使用我的鍵執行操作(例如左,右,上,下)。Java Swing中的關鍵動作監聽器
我做了一個名爲Frame的類,它擴展了JFrame並實現了動作偵聽器,在Stack Overflow上看到我需要在密鑰發佈函數中編寫我的代碼,以便在我按下鍵時運行代碼。
但是當我按下按鍵時什麼都沒有發生。
這裏是我的Java代碼:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Frame extends JFrame implements KeyListener {
private static final int BOARD_SIZE = 51;
private static final int FRAME_SIZE = 700;
private static final Color SNAKE = Color.GREEN;
private static final Color BOARD = Color.WHITE;
private static final Color FOOD = Color.BLUE;
private static enum DIRECTION {
right, left, up, down;
}
private static DIRECTION curr = DIRECTION.right;
public Frame() {
super.setTitle("<<SNAKE GAME>>");
super.setSize(this.FRAME_SIZE, this.FRAME_SIZE);
GridLayout layout = new GridLayout(this.BOARD_SIZE, this.BOARD_SIZE);
super.setLayout(layout);
int val = this.randomNum(this.BOARD_SIZE * this.BOARD_SIZE - 7);
int count = 0;
for (int i = 0; i < this.BOARD_SIZE; i++) {
for (int j = 0; j < this.BOARD_SIZE; j++) {
JButton btn = new JButton();
super.add(btn);
this.buttons[i][j] = btn;
if (i == this.BOARD_SIZE/2 + 1 && j > this.BOARD_SIZE/2 - 5
&& j <= this.BOARD_SIZE/2 + 6) {
this.snakeLL.snake.AddFirst(btn);
btn.setBackground(this.SNAKE);
} else if (count == val) {
btn.setBackground(FOOD);
count++;
} else {
btn.setBackground(this.BOARD);
count++;
}
}
}
super.addKeyListener(this);
super.setResizable(false);
super.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyLocation();
if (key == KeyEvent.VK_UP) {
this.curr = DIRECTION.up;
}
}