我无法从键盘获得任何输入,我不知道为什么。请更正我的代码以使其正常工作。
在我的程序中,我创建了一个扩展JFrame的Window,然后我创建了扩展JPanel的Panel,然后我将Panel添加到了我的Window。 Panel实现了KeyListener,并且还具有请求的焦点。
这是我的主要课程:
package dev.thomaslienbacher.spacefighter;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
public class Main {
public static Window window;
public static Panel panel;
public static int width = 0;
public static int height = 0;
public static final int FPS = 35;
public static void main(String[] args) {
panel = new Panel(FRAMEWIDTH, FRAMEHEIGHT);
ArrayList<Image> icons = new ArrayList<Image>();
icons.add(Utils.getImage("res/icon8.png"));
gameMechanics = new GameMechanics();
window = new Window(title, 606, 700, icons);
window.add(panel);
width = window.getContentPane().getSize().width;
height = window.getContentPane().getSize().height;
Timer gameLoopTimer = new Timer(1000 / FPS, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
panel.actionPerformed(null);
}}
);
gameLoopTimer.start();
}
}
这是我的Window类:
package dev.thomaslienbacher.spacefighter;
import java.util.ArrayList;
import javax.swing.JFrame;
public class Window extends JFrame{
public Window(String title, int width, int height, ArrayList<Image> icons){
super(title);
this.setFocusable(true);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setIconImages(icons);
this.setCursor(cross);
}
}
这是我的Panel类:
package dev.thomaslienbacher.spacefighter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class Panel extends JPanel implements ActionListener, KeyListener{
public Panel(int width, int height) {
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addKeyListener(this);
this.setBounds(0, 0, width, height);
this.requestFocusInWindow();
this.requestFocus();
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("Released");
}
@Override
public void keyTyped(KeyEvent e) {
}
}