[英]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.