13

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?

None
  • 3,875
  • 7
  • 43
  • 67

2 Answers2

21
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
  • 923
  • 1
  • 6
  • 12
7

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
  • 1,833
  • 1
  • 16
  • 18
  • Almost didn't up-vote this because of the use of GridBagLayout for such a simple need. – Lawrence Dol Oct 02 '10 at 01:27
  • 3
    Never use GridBagLayout! Never! – Denis Tulskiy Oct 02 '10 at 04:46
  • 5
    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 Oct 03 '10 at 16:30
  • 2
    There's nothing wrong with the GridBagLayout. It's flexible and easy to use, at least in my experience. If you encounter performance issues while laying out your components, then certainly check out other layout managers. – Håvard Geithus Feb 03 '14 at 21:59