对不起,我是java的初学者。对于我正在进行的小冒险游戏,我想在我的gameLoop中添加一个延迟来测试我的图形。
问题是我有一个循环,其中的东西在屏幕上得到printet / paintet(称之为你想要的:D)。当我这样做时,我没有任何问题,但是当我添加一个Thread.sleep(带有throws或try& catch)时,我在我的程序中的某个地方得到一个NullPointerExeption,这与我的代码无关:
GUI CLASS:
package xxx.yyy.zzz;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JPanel {
private JFrame frame;
private Control ctr;
final int objectSize = 10;
public GUI() {
frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(this);
ctr = new Control(this);
}
public static void main(String[] args) {
new GUI();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int x = 0; x < ctr.getScreenSizeX(); x = x + objectSize) {
for(int y = 0; y < ctr.getScreenSizeY(); y = y + objectSize) {
g.setColor(ctr.getScreen(x/objectSize, y/objectSize));
g.drawRect(x, y, objectSize, objectSize);
g.fillRect(x, y, objectSize, objectSize);
}
}
}
}
CONTROL CLASS:
package xxx.yyy.zzz;
import java.awt.Color;
public class Control {
private GUI gui;
private Level l1;
private Color[][] screen;
private Player player;
private final int screenSizeX = 400;
private final int screenSizeY = 300;
public Control(GUI pGUI) {
gui = pGUI;
l1 = new Level(400, 30, true);
screen = new Color[screenSizeX][screenSizeY];
player = new Player(Color.WHITE);
gameLoop();
}
private void gameLoop() {
print(l1);
for(int i = 0; i < 100; i++) {
player.move(1);
print(l1);
try {
Thread.sleep(100); //here is my problem!
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void print(Level pL) {
if(pL.getSizeX() > 40 || pL.getSizeX() > 40) {
for(int x = 0; x < 40; x++) {
for(int y = 0; y < 30; y++) {
screen[x][y] = pL.getObjectColor(x + (player.getX() - 10),
y);
}
}
}
else {
for(int x = 0; x < 40; x++) {
for(int y = 0; y < 30; y++) {
screen[x][y] = pL.getObjectColor(x, y);
}
}
}
gui.repaint();
}
public Color getScreen(int x, int y) {
return screen[x][y];
}
public int getScreenSizeX() {
return screenSizeX;
}
public int getScreenSizeY() {
return screenSizeY;
}
}
我审查了我的包xD
感谢您的回复,对不起我对游戏编程和编程初学者不熟悉!
编辑:我的错误日志:
线程中的异常&#34; AWT-EventQueue-0&#34;显示java.lang.NullPointerException 在com.zeptosi.snogg.GUI.paintComponent(GUI.java:31) ...