[英]Java - How to add text in JTextPane using Document
我想在我的Java應用程序中創建一個控制台(JTextPane),以顯示我的應用程序在做什么。 我嘗試使用不同的方法很多次,但是都失敗了……這是我代碼的一部分。
主類
private final Form form;
println("Downloading files...");
public void println(String line)
{
System.out.println(line);
form.getConsole().print(line);
}
表格(GUI)
private TabConsole console;
tabbedPane.addTab("Console", console);
public TabConsole getConsole()
{
return console;
}
Tab控制台
public void print(final String line) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
TabConsole.this.print(line);
}
});
return;
}
Document document = this.console.getDocument();
JScrollBar scrollBar = getVerticalScrollBar();
boolean shouldScroll = false;
if (getViewport().getView() == this.console) {
shouldScroll = scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4 > scrollBar.getMaximum();
}
try
{
document.insertString(document.getLength(), line, null);
} catch (BadLocationException localBadLocationException) {
}
if (shouldScroll)
scrollBar.setValue(2147483647);
}
我的代碼有什么問題嗎? 感謝您的幫助。
盡管代碼看起來正確,但是將BadLocationException重新拋出為RuntimeException。 你遇到了什么錯誤?
如果未顯示該文本,則可能是您更新了錯誤的文檔。 確保您正在更新TextArea所使用的文檔,或用於顯示內容的任何文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.