getting JTextPane to scroll

别说谁变了你拦得住时间么 提交于 2019-12-10 22:33:11

问题


How do I get JTextPane to scroll? In this example, JScrollPane is employed but as running the code will reveal, the scroll bar can be displayed but it is not functional.

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.*;

public class JTextPaneTester
{
    JTextPane jtp = new JTextPane();
    StyledDocument doc;
    Style style;
    JScrollPane jsp = new JScrollPane(jtp);

    JTextPaneTester()
    {
        doc = (StyledDocument)jtp.getDocument();
        style = doc.addStyle("fancy", null);
        jsp.setVerticalScrollBarPolicy(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    }

    void append(String s)
    {
        try
        {
            doc.insertString(doc.getLength(), s, style);
        }
        catch (BadLocationException e) { assert false: "problem"; }
    }

    public static void main(String[] args)
    {
        JTextPaneTester thing = new JTextPaneTester();

        for (int i = 0; i < 100; i++)
            thing.append("nouns verbs adjectives \n");

        JFrame f = new JFrame();
        JPanel center = new JPanel();
        f.add(center, BorderLayout.CENTER);

        center.add(thing.jsp);
        f.setSize(400, 400);
        f.setVisible(true);
    }
}

回答1:


If I place the snippet

for (int i = 0; i < 100; i++) {
      thing.append("nouns verbs adjectives \n");
}

after

f.setVisible(true);

it seems to work.



来源:https://stackoverflow.com/questions/7468550/getting-jtextpane-to-scroll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!