當我嘗試點擊空格鍵時,沒有任何反應。我用不同的鑰匙試過,但沒有任何效果。有人能告訴我我做錯了什麼嗎?或爲什麼這不工作?java - 爲什麼我的KeyListener不會做任何事情?
另外我正在使用Java SE 1.6來編譯這個。
這裏是我的代碼:
package bigbass1997;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class Main extends JFrame implements KeyListener, MouseListener, MouseMotionListener{
// VARIABLES
public static String title = "Royal Casino";
public static String author = "bigbass1997";
public static String version = "0.0.0";
GamePanel gp;
public Main(){
gp = new GamePanel();
this.setSize(GamePanel.gameDim);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setTitle(title + " " + version);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.addKeyListener(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.add(gp);
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE){
Slots.slotsThread.start();
System.out.println("Slot THREAD Started");
GamePanel.slotsplaying = true;
}
}
public static void main(String[] args) {
@SuppressWarnings("unused")
Main m = new Main();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
如何添加一個KeyListener的玻璃面板要解決的任擇議定書的問題? – 2012-01-16 02:45:06
-1,在問題中甚至建議用戶使用玻璃窗格? KeyEvents轉到具有焦點的組件。玻璃窗格默認是不可見的,所以它不會收到關鍵事件。這很好,你鏈接到Swing教程,但是,你應該鏈接到的部分是關於「如何使用鍵綁定」的部分。 Swing被設計爲使用鍵綁定,而不是鍵監聽器。 – camickr 2012-01-16 03:02:10
'在問題中,它甚至暗示用戶正在使用玻璃窗? Swing的基本知識告訴你,每個JFrame都有一個玻璃窗格。此外,將事件監聽器添加到玻璃窗格將使他們捕捉輸入事件。所以我爲什麼這樣回答。 – Flaise 2012-01-16 14:31:26