views:

41

answers:

2

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?

+2  A: 
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

jlewis42
+1  A: 

Place the JTextArea inside of a JScrollPane, and place that into the JPanel with with a layout that fixes the size. An example with a GridBagLayout, for instance could look like this:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());

JScrollPane scrollpane = new JScrollPane();
GridBagConstraints cons = new GridBagContraints();
cons.weightx = 1.0;
cons.weighty = 1.0;
panel.add(scrollPane, cons);

JTextArea textArea = new JTextArea();
scrollPane.add(textArea);

This is only a rough sketch, but it should illustrate how to do it.

Zoe Gagnon
Almost didn't up-vote this because of the use of GridBagLayout for such a simple need.
Software Monkey
Never use GridBagLayout! Never!
tulskiy
Through a long and complete annoyance with every other layout manager in Swing, I now use GridBagLayout almost exclusively. Thats an artifact of my personal history, rather than a recomendation. Please do use whichever layout manager fits your needs. In this case, I think the exact specification of the weights explicitly shows that the scroll pane absorbs all the changes in size. But, its certainly not worth actually using a complex layout manager for a simple layout.
Zoe Gagnon
Whats wrong with GridBagLayout anyway?
Zoe Gagnon