我正在尝试制作一个游戏,该游戏调用线程中有一段时间循环。我正在使用一个Jframe,该jframe按下按钮时基本上会切换屏幕。我要获得的是,当您按按钮时,它绘制瓷砖然后调用线程。但是,当我按下按钮时,它就会冻结。它停留在按下按钮且不会更改的屏幕上。请注意,如果我不调用线程,它确实会改变。另外,我尝试更改while循环的位置,但这也不起作用。
绘制脚本:
void loadLevel(String level) {
panel.remove(searchTA);
panel.remove(titleL);
panel.remove(search2B);
panel.repaint();
this.level = level;
int x = 160;
int y = 140;
int tile = 0;
int line = 0;
for (int i = 0; i < 13; i++) {
for (int j = 0; j < 13; j++) {
String formula = (String
.valueOf(readFile("resources/Base Levels/Back Layer/" + level, line).charAt(tile))
+ String.valueOf(readFile("resources/Base Levels/Front Layer/" + level, line).charAt(tile)));
if (formula.equals("00")) {
try {
BufferedImage img;
BufferedImage c;
img = ImageIO.read(clear);
c = resize(img, 50, 50);
JLabel lb = new JLabel(new ImageIcon(c));
lb.setLocation(x, y);
lb.setSize(50, 50);
panel.add(lb);
} catch (IOException e) {
e.printStackTrace();
}
} else if (formula.equals("01")) {
try {
BufferedImage img;
BufferedImage c;
img = ImageIO.read(goal);
c = resize(img, 50, 50);
JLabel lb = new JLabel(new ImageIcon(c));
lb.setLocation(x, y);
lb.setSize(50, 50);
panel.add(lb);
} catch (IOException e) {
e.printStackTrace();
}
} else if (formula.equals("02")) {
try {
BufferedImage img;
BufferedImage c;
img = ImageIO.read(wall);
c = resize(img, 50, 50);
JLabel lb = new JLabel(new ImageIcon(c));
lb.setLocation(x, y);
lb.setSize(50, 50);
panel.add(lb);
} catch (IOException e) {
e.printStackTrace();
}
}
x = x + 50;
tile++;
}
tile = 0;
line++;
x = 160;
y = y + 50;
}
play.run();
}
线程:
public Thread play = new Thread(new Runnable() {
public void run() {
panel.revalidate();
panel.repaint();
String tileOn = new String();
String[] tiles = new String[169];
int tile = 0;
for (int i = 1; i < 14; i++) {
for (int b = 1; b < 14; b++) {
tiles[tile] = String
.valueOf(readFile("resources/Base Levels/Back Layer/" + level, i - 1).charAt(b - 1))
+ String.valueOf(readFile("resources/Base Levels/Front Layer/" + level, i - 1).charAt(b - 1));
tile++;
}
}
while (!tileOn.equals("01")) {
}
}
});
当我说冻结时,我的意思是冻结。甚至都没有按Jframe右上角的X关闭它。我必须回到日食(IDE)并停止脚本。另外,我知道while循环引起了问题,因为我尝试删除时循环并起作用。
您的问题是Johny Rathbone Answser中提到的问题的组合以及对该答案的评论。
在您的时循环中,您在将其初始化为新字符串后才进行while (!tileOn.equals("01"))
。因此,这将是一个无循环。但是,这应该没问题,因为您尝试在背景线程上运行它。
但是,通过使用play.run()
而不是play.start()
,您可以在主线程上运行。
这两种方法的区别在于start()
实际上启动了一个新线程并在其上执行run()
方法,而调用run()
将在主线程上执行run()
方法。
因此,如果将play.run()
更改为play.start()
,则应取消冻结
while (!tileOn.equals("01")) {
此行是您唯一对" Tileon"的引用,除了您称其为新字符串时。由于那里不等于" 01",因此这将永远是正确的。而且,由于循环中没有任何内容,因此while循环总是会运行,因为那个循环中没有什么可以打破条件的。