2011-09-19 68 views
2

如何讓JTextPane滾動?在這個例子中,JScrollPane被使用,但是作爲運行代碼將會顯示,滾動條可以被顯示,但它不起作用。讓JTextPane滾動

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

如果我把該代碼段

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

f.setVisible(true); 

它似乎工作。