代碼:也不太清楚爲什麼我的KeyListener不在這裏工作了
public class Panel extends JPanel implements KeyListener{
//variable for coordinates:
private final int a1 = 155;
private final int a2 = (790-a1);
private final int a5 = 47;
private boolean gameStarted = false;
private int rotated = 0;
ArrayList<TetrisBlocks> blocks = new ArrayList<TetrisBlocks>();
public Panel() //constructor
{
setPreferredSize(new Dimension(1440,790)); //sets the size of the window displayed
setBackground(Color.blue); //sets background color to blue (of the JPanel)
setLayout(new SpringLayout()); //sets the layout of the text
addKeyListener(this);
setFocusable(true);
//adds text for Game:
add(printText(" Horizontal Tetris"));
add(printText(" Score:"));
//creates arrayList of Tetris Blocks:
for (int i = 0; i <1; i++){
blocks.add(new TetrisBlocks(1));
}
}
public boolean getValue(){
return gameStarted;
}
public void paintComponent(Graphics g){
super.paintComponent(g); //overrides the paint method
Graphics2D graphicsA = (Graphics2D) g; //creates a new Graphics 2D object
}
public JLabel printText(String input){
JLabel jlabel1 = new JLabel(input); //create a new label for the text
jlabel1.setFont(new Font("Verdana",Font.BOLD,40)); //set font type and size
return jlabel1; //return statement for the method
}
public void AutomaticMove(){
int x = 1;
while (x <= 6){
repaint();
if (rotated == 1 || rotated == 3){
blocks.get(0).MoveY();
} else{
blocks.get(0).MoveX();
}
x+=1;
try { //gives computer a 1 second delay before moving the block again
Thread.sleep(500);
} catch (InterruptedException e) { //throws and catches the exception when the sleep is interrupted
e.printStackTrace();
}
}
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key typed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key typed");
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
}
一直在嘗試很多不同的東西,但關鍵的聽衆就是不給我在鍵盤上輸入作出響應。任何建議或想法,爲什麼這可能是真實的?我已經在網上嘗試了很多其他來源,但仍然無法弄清楚爲什麼關鍵聽衆不能在我的程序中工作。我的IDE或我的電腦沒有問題,因爲使用keylistener的其他代碼工作得很好。
這只是一個猜測,所以我做它一個評論,而不是答案。您正在將此keyListener添加到此面板中,但是關鍵事件是否會進入面板?我習慣於將keyListener添加到幀中,以便幀在焦點時獲取事件。也許你的面板只有在焦點時才能獲得關鍵事件。 – arcy
歡迎來到SO。 TL; DR。請發帖[mcve] – c0der