简体   繁体   中英

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. 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)

private TabConsole console;

tabbedPane.addTab("Console", console);

public TabConsole getConsole()
{
        return console;
}

TabConsole

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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