基本上我试图做的是不断追加一个字符串文本到用户单击按钮时JTextPane。只有当用户再次点击按钮时,循环才会停止。这是在我的按钮的actionPerformed方法:如何阻止JButton执行无限循环
StyledDocument xpInfo = txtXPInfo.getStyledDocument();
if (btnGo.getText().equals("Go Adventure!")) {
btnGo.setText("Stop Adventure");
try {
do {
xpInfo.insertString(xpInfo.getLength(), "Some string\n", null);
txtXPInfo.update(txtXPInfo.getGraphics());
Thread.sleep(1000);
} while (btnGo.getText().equals("Stop Adventure"));
} catch (BadLocationException e) {
System.out.println(e);
} catch (InterruptedException ex) {
Logger.getLogger(FrmPlay.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (btnGo.getText().equals("Stop Adventure")) {
btnGo.setText("Go Adventure!");
}
我写的代码似乎是一个无限循环。我认为这可能是因为我在按钮的actionPerformed方法中完成了所有这些操作,但我不知道如何实现它。如果这是一个愚蠢的问题,我很抱歉。我事先感谢任何愿意回答这个问题的人!
虽然我不做摇摆,睡觉,或像循环这在事件线程上是一个坏主意。 [你也许应该看看定时器。](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) – WalterM
@WalterM我研究过它,我可能会把它变成一个定时器。我不知道如何延迟使用Thread.sleep(),这是我使用的。而且我知道循环是一个糟糕的主意,我不知道如何才能使其工作。无论如何感谢您的建议! – Grandevox