2010-04-21 87 views
11

我無法獲得JTextArea滾動。我不確定你如何搞砸JScrollPane,但我似乎有,我只是看不到它。它是更大項目的一部分,但下面的代碼是我如何創建JTextArea並將其添加到JScrollPane。當您在文本區域的邊緣之外鍵入時,滾動條不會出現。將垂直滾動條設置爲始終打開會使滾動條無法執行任何操作。JScrollPane中的JTextArea上的滾動條不起作用

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

public class TextAreaTest extends JFrame{ 

    public TextAreaTest() { 
    super("Text Area Scroller"); 

    Container c = getContentPane(); 

    JTextArea textarea = new JTextArea(); 
    textarea.setPreferredSize(new Dimension(300, 50)); 
    textarea.setLineWrap(true); 
    textarea.setText("xx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\nxx\n"); 

    JScrollPane scroller = new JScrollPane(textarea); 

    c.add(scroller, BorderLayout.CENTER); 
    pack(); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String args[]){ 
    TextAreaTest instance = new TextAreaTest(); 
    instance.setVisible(true); 
    } 
} 

我已經嘗試在構造函數中設置文本區域文本或行和列,這兩者都沒有工作。這是我的目標。任何想法?

回答

26

設置滾動窗格的首選大小而不是文本區域。

+0

謝謝!出於某種原因,我認爲我已經嘗試過,但失敗了,但它的工作很好。乾杯。 – Robert 2010-04-21 22:53:06

+0

+1 - 將'setPreferredSize'完全移除到文本區域,或者如果您想要設置大小,請將它設置在'scrollPane'上。 – 2010-04-21 22:54:26

+2

我在NetBeans 7.3中使用Swing佈局編輯器。爲了做到這一點,我必須將JTextArea的PreferredSize屬性設置爲null。當我這樣做時,垂直滾動條神奇地出現了。 – 2013-04-30 14:10:02

1

其他人都是正確的大小。順便說一句,考慮開始對事件指派線程(EDT):

public static void main(String args[]) { 
    EventQueue.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      new TextAreaTest().setVisible(true); 
     } 
    }); 
} 
-1

使用此代碼

import javax.swing.*; 
public class ScrollingTextArea 
{ 
JFrame f; 
JTextArea ta; 
JScrollPane scrolltxt; 

public ScrollingTextArea() 
{ 
    // TODO Auto-generated constructor stub 

    f=new JFrame(); 
    f.setLayout(null); 
    f.setVisible(true); 
    f.setSize(500,500); 
    ta=new JTextArea(); 
    ta.setBounds(5,5,100,200); 

    scrolltxt=new JScrollPane(ta); 
    scrolltxt.setBounds(3,3,400,400); 

    f.add(scrolltxt); 

} 

public static void main(String[] args) 
{ 
    new ScrollingTextArea(); 
} 

}