该类用于在您按空格键时启动我制作的游戏,然后在游戏结束屏幕中按空格键时重新启动空格。当我按空格键并按预期启动游戏时,它第一次起作用,但是当我通过屏幕进入游戏并按空格键时,什么也没有发生。我试图扩展 JFrame 而不是 JApplet,然后它工作得很好。
这是我的代码:
package Game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GameTest extends JApplet{
private PAPITest papi;
private TestPane panel;
private boolean inMenu = true;
private ImageIcon ii;
private Image image;
public void init(){
setFocusable(true);
requestFocusInWindow();
requestFocus();
ii = new ImageIcon("Ball Jump.png");
image = ii.getImage();
papi = new PAPITest();
panel = new TestPane();
add(panel);
setSize(600,600);
setVisible(true);
}
public void paint(Graphics g){
if(inMenu == true){
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(image, 0, 0, this);
repaint();
}
}
public class TestPane extends JPanel {
public TestPane() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true), "released");
am.put("pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(inMenu == true){
inMenu = false;
remove(panel);
papi.setSize(600,600);
papi.setAlive(true);
add(papi);
setVisible(true);
}
if (papi.isAlive() != true){
remove(papi);
papi = new PAPITest();
papi.setSize(600,600);
add(papi);
setVisible(true);
repaint();
}
}
});
am.put("released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(inMenu == true){
inMenu = false;
remove(panel);
papi.setSize(600,600);
papi.setAlive(true);
add(papi);
setVisible(true);
}
if (papi.isAlive() != true){
remove(papi);
papi = new PAPITest();
papi.setSize(600,600);
add(papi);
setVisible(true);
repaint();
}
}
});
setFocusable(true);
requestFocusInWindow();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(image, 0, 0, this);
repaint();
}
}
}