Java JTextArea that auto-resizes and scrolls

None picture None · Oct 2, 2010 · Viewed 26.4k times · Source

I have a JTextArea in a JPanel. How can I have the JTextArea fill the whole JPanel and resize when the JPanel resizes and scroll when too much text is typed in?

Answer

jlewis42 picture jlewis42 · Oct 2, 2010
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());  //give your JPanel a BorderLayout

JTextArea text = new JTextArea(); 
JScrollPane scroll = new JScrollPane(text); //place the JTextArea in a scroll pane
panel.add(scroll, BorderLayout.CENTER); //add the JScrollPane to the panel
// CENTER will use up all available space

See http://download.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.html or http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html for more details on JScrollPane