我无法从键盘得到任何输入,我不知道为什么。请更正我的代码,使它工作。
在我的程序中,我创建了一个扩展jframe的窗口,然后创建了扩展jpanel的面板,然后将面板添加到我的窗口中。该面板实现了keylister,并且还请求了焦点。
这是我的主要课程:
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();
}
}
这是我的窗口类:
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);
}
}
这是我的小组课:
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) {
}
}
暂无答案!
目前还没有任何答案,快来回答吧!