如何让JTextPane滚动?在这个例子中,使用了JScrollPane,但是当运行代码显示时,滚动条可以显示但不起作用。
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);
}
}
答案 0 :(得分:1)
如果我放置代码段
for (int i = 0; i < 100; i++) {
thing.append("nouns verbs adjectives \n");
}
之后
f.setVisible(true);
它似乎有效。