基本上我試圖做的是不斷追加一個字符串文本到用戶單擊按鈕時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