JTextArea simple example with scrolling - Musings

By: Nicholas Duchon

This example produces two JFrames, each with four buttons in a panel on the bottom and a scrolling JTextArea in the center of the frame.

Notice the use of the JTextArea as an INSTANCE variable.

Since putStuff is an instance method, and jta (the JTextArea) is an instance variable, the method can access jta directly, and the method accesses the jta of the particular instance - which you can see is specified in the use of the variables jb and jf in main.


// File: TextAreaExample.java// Author: Nicholas Duchon
// Date: Oct 28, 2010
// Purpose: A simple example showing how to use 
//    JTextArea in the CENTER of a BorderLayout
//    such as the default in a JFrame.
// > Also, add a panel of buttons to the bottom
// > This creates TWO JFrames, one on top of the other
//       each with its own text area

import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;

public class TextAreaExample extends JFrame {
  static final long serialVersionUID = 25;
  static Random rn = new Random ();
  JTextArea jta = new JTextArea ();  

  public TextAreaExample (String t) {
    setTitle (t);
    setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo (null);
    setSize (300, 300);
    setVisible (true);

    // put scroll bars around the text area
    JScrollPane sp = new JScrollPane (jta);
    add (sp, BorderLayout.CENTER); 

    // buttons on the bottom
    JPanel pb = new JPanel (); // FlowLayout
    pb.add (new JButton ("one"));
    pb.add (new JButton ("two"));
    pb.add (new JButton ("three"));
    pb.add (new JButton ("four"));
    add (pb, BorderLayout.PAGE_END);
  } // end constructor
  public void putStuff () {
    StringBuffer sb = new StringBuffer ();
    for (int i = 1; i <= 3000; i++)
      sb.append ((i%100 == 0)?'\n':(char)(rn.nextInt(26) + 'a'));
    jta.append (sb.toString ());
  } // end putStuff
  public static void main (String args []) {
    TextAreaExample jf = new TextAreaExample ("First");
    jf.putStuff ();
    TextAreaExample jb = new TextAreaExample ("Second");
    jb.putStuff ();
  } // end main
} // end class TextAreaExample