简体   繁体   English

Java-如何使用文档在JTextPane中添加文本

[英]Java - How to add text in JTextPane using Document

I want to make a console(JTextPane) in my Java application to show that what is my application doing. 我想在我的Java应用程序中创建一个控制台(JTextPane),以显示我的应用程序在做什么。 I had tried a lot of times using different method but failed...Here is some part of my code. 我尝试使用不同的方法很多次,但是都失败了……这是我代码的一部分。

MainClass 主类

private final Form form;

println("Downloading files...");

public void println(String line)
{
        System.out.println(line);
        form.getConsole().print(line);
}

Form(GUI) 表格(GUI)

private TabConsole console;

tabbedPane.addTab("Console", console);

public TabConsole getConsole()
{
        return console;
}

TabConsole 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);
      }

Is that anything wrong with my codes? 我的代码有什么问题吗? Thanks for helping. 感谢您的帮助。

rethrow the BadLocationException as a RuntimeException, although the code looks correct. 尽管代码看起来正确,但是将BadLocationException重新抛出为RuntimeException。 What error are you getting? 你遇到了什么错误?

If the text is not showing up, you are probably updating the wrong Document. 如果未显示该文本,则可能是您更新了错误的文档。 Be sure you're updating the Document which is used by your TextArea, or whatever you're using to display the contents. 确保您正在更新TextArea所使用的文档,或用于显示内容的任何文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM