---
Abbey Workshop

Java: Creating a Scrolling Text Area

This tip covers the basic technique for creating a standard text area that has the following features

The complete code for this example is linked from the bottom of this page. The lines of code below show the basic steps for creating the text area.

The key lines are described as follows:

ta_scroll.java (Click to get source)

   1:import javax.swing.*;
   2:import java.awt.*;
   3:import java.awt.event.*;
   4:
   5:public class ta_scroll{
   6:    private JFrame f; //Main frame
   7:    private JTextArea ta; // Text area
   8:    private JScrollPane sbrText; // Scroll pane for text area
   9:    private JButton btnQuit; // Quit Program
  10:    
  11:    public ta_scroll(){ //Constructor
  12:        // Create Frame
  13:        f = new JFrame("Swing Demo");
  14:        f.getContentPane().setLayout(new FlowLayout());
  15:        
  16:        // Create Scrolling Text Area in Swing
  17:        ta = new JTextArea("", 5, 50);
  18:        ta.setLineWrap(true);
  19:        sbrText = new JScrollPane(ta);
  20:        sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  21:        
  22:        // Create Quit Button
  23:        btnQuit = new JButton("Quit");
  24:        btnQuit.addActionListener(
  25:            new ActionListener(){
  26:                public void actionPerformed(ActionEvent e){
  27:                    System.exit(0);         
  28:                }
  29:            }
  30:        );
  31:        
  32:    }
  33:
  34:    public void launchFrame(){ // Create Layout
  35:        // Add text area and button to frame
  36:        f.getContentPane().add(sbrText);
  37:        f.getContentPane().add(btnQuit);
  38:        
  39:         // Close when the close button is clicked
  40:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  41:
  42:        //Display Frame
  43:        f.pack(); // Adjusts frame to size of components
  44:        f.setVisible(true);
  45:    }
  46:    
  47:    public static void main(String args[]){
  48:        ta_scroll gui = new ta_scroll();
  49:        gui.launchFrame();
  50:    }
  51:}