我正在进行一场简单的Pong游戏。当用户按下空格键时,游戏开始。在Windows XP中运行良好,但在Windows 7中变得非常奇怪。如果按空格键,然后单击游戏窗口,它将运行。如果你先点击,然后点击空格,没有。我已粘贴下面的主要课程。
public class Game extends JPanel {
static final int FW = 400;
static final int FH = 300;
Ball ball = new Ball(this);
Paddle paddleL = new Paddle(this);
PaddleAI paddleR = new PaddleAI(this);
public static boolean go;
static KeyListener key;
public Game(){
setFocusable(true);
addKeyListener(key = new KeyListener(){
@Override
public void keyTyped(KeyEvent e){
}
@Override
public void keyReleased(KeyEvent e){
paddleL.keyReleased(e);
if(e.getKeyCode() == KeyEvent.VK_SPACE)
go = true;
}
@Override
public void keyPressed(KeyEvent e){
paddleL.keyPressed(e);
if(e.getKeyCode()==KeyEvent.VK_SPACE)
go = true;
}
});
}
void setup(){
ball.setup();
paddleL.setup();
paddleR.setup();
}
void move(){
ball.move();
paddleL.move();
paddleR.move();
}
public void paint(Graphics g){
super.paint(g);
ball.paint(g);
paddleL.paint(g);
paddleR.paint(g);
}
public static void main(String[] args) throws InterruptedException{
//final int FW = 400;
// final int FH = 300;
JFrame frame = new JFrame();
Game game = new Game();
game.setBackground(Color.black);
frame.add(game);
frame.getContentPane().setBackground(Color.cyan);
frame.setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FW, FH);
frame.setLocationRelativeTo(null);
frame.setTitle("Pong");
frame.setResizable(true);
frame.setVisible(true);
game.setup();
while(true){
if(go){
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
}
答案 0 :(得分:2)
您将要使用键绑定而不是键侦听器。 KeyListener非常挑剔关注哪个组件,这是您遇到的问题。以下是如何使用Key Binding:
的快速示例import java.awt.event.*;
import javax.swing.*;
public class KeyBindings extends Box{
public KeyBindings(){
super(BoxLayout.Y_AXIS);
final JTextPane textArea = new JTextPane();
textArea.insertComponent(new JLabel("Text"));
add(textArea);
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("New Text");
}};
String keyStrokeAndKey = "control SPACE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
textArea.getActionMap().put(keyStrokeAndKey, action);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new KeyBindings());
frame.pack();
frame.setVisible(true);
}
}