gpt4 book ai didi

java - 使用 While 循环卡住整个脚本

转载 作者:行者123 更新时间:2023-12-02 12:14:29 24 4
gpt4 key购买 nike

我正在尝试制作一个游戏,该游戏调用一个有 while 循环的线程。我使用的 JFrame 基本上可以在您按下按钮时切换屏幕。我想要得到的是,当您按下按钮时,它会绘制图 block ,然后调用线程。但当我按下按钮时,它就卡住了。它停留在按下按钮的屏幕上并且不会改变。请注意,如果我不调用线程,它确实会改变。我也尝试过更改 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 也无法关闭它。我必须返回 Eclipse (IDE) 并停止脚本。另外,我知道 while 循环导致了问题,因为我尝试删除 while 循环并且它起作用了。

最佳答案

您的问题是 Johny Rathbone 的答案中提到的问题以及对该答案的评论的组合。

在 while 循环中,您在将其初始化为新字符串后执行 while (!tileOn.equals("01")) 。因此这将是一个 andless 循环。不过,这应该没问题,因为您尝试在后台线程上运行它。

但是,通过使用 play.run() 而不是 play.start(),您可以在主线程上运行它。

这两个方法的区别在于 start() 实际上启动了一个新线程并在其上执行 run() 方法,同时调用 run( ) 将在主线程上执行 run() 方法。

因此,如果将 play.run() 更改为 play.start() 它应该会解冻

关于java - 使用 While 循环卡住整个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com