0
我遇到了我的小程序问题。它的目的是创建一个游戏,您可以在屏幕底部移动一个块,以适应从上面掉落的块中的洞。我已经实现了这个块,但是当我按下一个键时我无法移动这个块。 这里是我的源代码:简单的小程序游戏错误
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MathewBorumGame extends JApplet
{
public void init()
{
Dimension dim = getSize();
MathewBorumGamePanel avoidance = new MathewBorumGamePanel(dim);
add(avoidance);
Thread game = new Thread(avoidance);
game.start();
}
}// end of the extended JApplet class
class MathewBorumGamePanel extends JPanel implements Runnable{
protected int x = 225;
protected int y = 450;
private int speed = 0;
private boolean isPlaying = false;
private boolean hasHit = false;
private String instructions = "Press 'Enter' to start survive as long as"
+ " as possible.";
private String keyInstructions = "Use arrow keys to move.";
private String test;
private Dimension dim = null;
private Thread game = null;
private Timer timer = new Timer(1000, new TimerListener());
public MathewBorumGamePanel(Dimension paramDimension) {
this.dim = paramDimension;
setBackground(new Color(255, 255, 204));
setForeground(Color.black);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(x >= 10) x = x - 10;
repaint();
break;
case KeyEvent.VK_RIGHT:
if(x <= 490) x = x + 10;
repaint();
break;
default:
repaint();
break;
}
}
});
}
public void run() {
for (;;) {
repaint();
}
}
public void paintComponent(Graphics paramGraphics) {
super.paintComponent(paramGraphics);
paramGraphics.fillRect(x, y, 50, 15);
paramGraphics.setFont(new Font("Serif", Font.BOLD, 15));
paramGraphics.drawString(this.instructions, 30, 30);
paramGraphics.drawString(this.keyInstructions, 30, 50);
test = test.valueOf(x);
paramGraphics.drawString(test, 30, 70);
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}//end of the extended JPanel class
感谢
覆盖'公共无效漆(图形paramGraphics)',而不是'的paintComponent( )'。另外,我不确定你的方法是否正确,因为我看着你无限循环重绘,但也有一个计时器触发每秒,并且是什么......重绘。但是,我无法看到您启动计时器的位置,所以让我们认为这是您最终工作的一个非常原始的版本:)让我知道我的提示的结果。 – Noe 2013-05-14 13:45:31
@Noe *“Override public void'paint(Graphics paramGraphics)''而不是'paintComponent()'。”*错! – 2013-05-14 13:47:31
特别是,“Swing程序应该重写'paintComponent()'而不是重写'paint()'。” - [* AWT和Swing中的绘画:绘画方法*](http://www.oracle.com/technetwork /java/painting-140037.html#callbacks) – trashgod 2013-05-15 03:58:56