我正在尝试用 Java 制作 2D 游戏,但是当我在线程中调用 repaint() 方法时,会出现一个奇怪的仅灰色窗口。
这是我到目前为止的源代码:
太空射手.java
package spaceshooter; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Spaceshooter extends JFrame implements KeyListener, Runnable { private Player player = new Player(5, 186, this); private boolean up, down; public Spaceshooter(String title) { super(title); this.setFocusable(true); this.addKeyListener(this); } @Override public void paint(Graphics gr) { super.paint(gr); gr.setColor(Color.BLACK); gr.fillRect(0, 0, 800, 500); player.paintPlayer(gr); } public static void main(String[] args) { Spaceshooter shooter = new Spaceshooter("Spaceshooter"); new Thread(shooter).start(); shooter.setSize(800,500); shooter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); shooter.setVisible(true); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 38) { up = true; down = false; } else if (e.getKeyCode() == 40) { down = true; up = false; } } @Override public void keyReleased(KeyEvent e) { down = false; up = false; } @Override public void run() { while(true) { if (up) { player.moveUp(); } else if (down) { player.moveDown(); } repaint(); try { Thread.sleep(20); } catch (InterruptedException ex) { Logger.getLogger(Spaceshooter.class.getName()).log(Level.SEVERE, null, ex); } } } }
播放器.java
package spaceshooter; import java.awt.Component; import java.awt.Graphics; import java.awt.Toolkit; public class Player { private int x, y; private Component comp; public Player(int x, int y, Component comp) { this.x = x; this.y = y; this.comp = comp; } public void moveUp() { y -= 5; } public void moveDown() { y += 5; } public void paintPlayer(Graphics gr) { gr.drawImage(Toolkit.getDefaultToolkit().getImage("images/player.png"), x, y, comp); } }
提前感谢您的回答!