Header javaperspective.com
JavaPerspective.com  >   Advanced Tutorials  >   1. Advanced GUI Features  >   1.5. Text areas

1.5. Text areas
Last updated: 1 January 2013.

This tutorial will show you how to use text areas in Java.

A text area is an instance of the class JTextArea. It is a component that displays text in multiple lines. You may have already seen basic examples of text areas in the previous tutorials. The purpose of this tutorial is to explore in more depth some of the features provided by text areas. Notably, you will see how to develop a simple plain text editor with Swing.

Usually, text areas are displayed within scroll panes. The following sample creates a text area and wraps a scroll pane around it.

JTextArea textArea = new JTextArea();
JScrollPane scrollPane =
new JScrollPane(textArea);

The scroll bars will appear only when needed, that is, when the content of the text area gets larger than its display area. If you want a different behaviour, you can use the constructor JScrollPane(Component view, int vsbPolicy, int hsbPolicy) to specify a vertical and horizontal scroll bar policy. The possible values for the argument vsbPolicy are JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED (the default) and JScrollPane.VERTICAL_SCROLLBAR_NEVER. Likewise, the possible values for the argument hsbPolicy are JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED (the default) and JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.

By default, text areas are editable. The superclass JTextComponent provides the method setEditable(boolean b) which allows you to make a text area editable or uneditable.

The next picture is an expanded version of the GUI shown in the tutorial File choosers (section 5.26.5). As you can see, the GUI is a basic plain text editor which uses BorderLayout to lay out its components like this: a series of buttons at the top and a text area in the center.


Text area example


Note that the series of buttons at the top can be replaced by a menu or a tool bar.

Here is how the buttons work:
The code follows:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.undo.UndoManager;

public final class TextAreas extends JFrame implements ActionListener {

   
private JButton openButton;
   
private JButton saveButton;
   
private JButton cutButton;
   
private JButton copyButton;
   
private JButton pasteButton;
   
private JButton searchButton;
   
private JButton selectAllButton;
   
private JButton undoButton;
   
private JButton redoButton;

   
private JTextArea textArea;

   
private JFileChooser fileChooser;

   
private JDialog searchDialog;
   
private int indexOfMatchFound;
   
private JTextField searchTextField;
   
private DefaultHighlighter.DefaultHighlightPainter greenHighLight;

   
private UndoManager undoManager;


   
public TextAreas() {
         
init();
          addComponents
();

          fileChooser =
new JFileChooser();

          setUpTheSearchDialog
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
public void actionPerformed(ActionEvent e) {

         
if(e.getSource().equals(openButton)){
               
// Show the open file chooser
               
int choice = fileChooser.showOpenDialog(this);

               
if(choice == JFileChooser.APPROVE_OPTION){
                     
// Get the selected file
                     
File selectedFile = fileChooser.getSelectedFile();

                     
// Open the file
                     
try{
                           
textArea.setText("");
                            BufferedReader reader =
new BufferedReader(new FileReader(selectedFile));

                           
for(String line = reader.readLine(); line != null; line = reader.readLine())
                                 
textArea.append(line + "\n");

                            reader.close
();
                     
}
                     
catch(Exception ex){
                           
ex.printStackTrace();
                     
}

                     
// Set the frame's title to the absolute path of the selected file
                     
setTitle(selectedFile.getAbsolutePath());
               
}
          }
         
else if(e.getSource().equals(saveButton)){
               
// Show the save file chooser
               
int choice = fileChooser.showSaveDialog(this);

               
if(choice == JFileChooser.APPROVE_OPTION){
                     
// Get the selected file
                     
File selectedFile = fileChooser.getSelectedFile();

                     
if(selectedFile.exists()){ // The file already exists
                           
choice = JOptionPane.showConfirmDialog(this, "The file already exists. Overwrite?", "Please confirm", JOptionPane.YES_NO_OPTION);
                           
if(choice == JOptionPane.YES_OPTION){
                                 
// Save the file
                                 
try{
                                       
BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile));
                                        writer.write
(textArea.getText());
                                        writer.close
();
                                 
}
                                 
catch(Exception ex){
                                       
ex.printStackTrace();
                                 
}
                            }
                           
else if(choice == JOptionPane.NO_OPTION){
                                 
// Do nothing
                           
}
                           
else if(choice == JOptionPane.CLOSED_OPTION){
                                 
// Do nothing (the user has closed the dialog without clicking a button)
                           
}
                      }
                     
else{ // The file does not exist
                            // Save the file
                           
try{
                                 
BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile));
                                  writer.write
(textArea.getText());
                                  writer.close
();
                           
}
                           
catch(Exception ex){
                                 
ex.printStackTrace();
                           
}
                      }

                     
// Set the frame's title to the absolute path of the selected file
                     
setTitle(selectedFile.getAbsolutePath());
               
}
          }
         
else if(e.getSource().equals(cutButton)){
               
textArea.cut();
         
}
         
else if(e.getSource().equals(copyButton)){
               
textArea.copy();
         
}
         
else if(e.getSource().equals(pasteButton)){
               
textArea.paste();
         
}
         
else if(e.getSource().equals(searchButton)){
               
searchDialog.setVisible(true);
         
}
         
else if(e.getSource().equals(selectAllButton)){
               
textArea.selectAll();
                textArea.requestFocus
();
         
}
         
else if(e.getSource().equals(undoButton)){
               
if(undoManager.canUndo())
                     
undoManager.undo();
         
}
         
else if(e.getSource().equals(redoButton)){
               
if(undoManager.canRedo())
                     
undoManager.redo();
         
}
    }


   
private JButton addButton(String name, Container container, int width, int height){
         
// Create the button
         
JButton button = new JButton(name);

         
// Set the preferred size to the specified value and set the border
         
button.setPreferredSize(new Dimension(width, height));
          button.setBorder
(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));

         
// Register the action listener on the button
         
button.addActionListener(this);

         
// Add the button to the container
         
container.add(button);

         
// Return the button
         
return button;
   
}


   
private void addComponents() {
         
// Set up the content pane
         
JPanel contentPane = new JPanel();
          contentPane.setLayout
(new BorderLayout());

         
// Set up the buttons panel ---------------------------------------------------------------------
         
JPanel buttonsPanel = new JPanel(); // Leave the layout to the default FlowLayout

         
int buttonWidth = 70;
         
int buttonHeight = 25;

          openButton = addButton
("Open", buttonsPanel, buttonWidth, buttonHeight);
          saveButton = addButton
("Save", buttonsPanel, buttonWidth, buttonHeight);
          cutButton = addButton
("Cut", buttonsPanel, buttonWidth, buttonHeight);
          copyButton = addButton
("Copy", buttonsPanel, buttonWidth, buttonHeight);
          pasteButton = addButton
("Paste", buttonsPanel, buttonWidth, buttonHeight);
          searchButton = addButton
("Search", buttonsPanel, buttonWidth, buttonHeight);
          selectAllButton = addButton
("Select All", buttonsPanel, buttonWidth, buttonHeight);
          undoButton = addButton
("Undo", buttonsPanel, buttonWidth, buttonHeight);
          redoButton = addButton
("Redo", buttonsPanel, buttonWidth, buttonHeight);

          contentPane.add
(buttonsPanel, BorderLayout.PAGE_START);
         
// -------------------------------------------------------------------------------------------------


          // Create the text area
         
textArea = new JTextArea();

         
// Set a custom font
         
textArea.setFont(new Font("Times New Roman", Font.PLAIN, 15));

         
// Instantiate undoManager and register it as an undoable edit listener on the text area's Document (the underlying data model)
         
undoManager = new UndoManager();
          textArea.getDocument
().addUndoableEditListener(undoManager);

         
// Wrap a scroll pane around the text area and add it to the content pane
         
JScrollPane scrollPane = new JScrollPane(textArea);
          contentPane.add
(scrollPane, BorderLayout.CENTER);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void setUpTheSearchDialog(){
         
greenHighLight = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
          searchTextField =
new JTextField();

          searchTextField.addActionListener
(new ActionListener() {
               
public void actionPerformed(ActionEvent e) {
                     
// Get user input
                     
String userInput = searchTextField.getText();

                     
if(! userInput.equals("")){
                           
// Get the index of the next match found within the text contained in 'textArea', starting at the caret position
                           
indexOfMatchFound = textArea.getText().toUpperCase().indexOf(userInput.toUpperCase(), textArea.getCaretPosition());

                           
try{
                                 
// Remove the previous highlight (if any) and highlight the match found
                                 
textArea.getHighlighter().removeAllHighlights();
                                  textArea.getHighlighter
().addHighlight(indexOfMatchFound, indexOfMatchFound + userInput.length(), greenHighLight);

                                 
// Set the caret position to the end of the match found
                                 
textArea.setCaretPosition(indexOfMatchFound + userInput.length());
                           
}
                           
catch(BadLocationException ev){
                                 
// Do nothing
                           
}
                      }
                }
          })
;

         
// Set up the search dialog
         
searchDialog = new JDialog(this, "Search");
          searchDialog.add
(searchTextField);
          searchDialog.setSize
(150, 50);
          searchDialog.setLocationRelativeTo
(this);
          searchDialog.setResizable
(false);

          searchDialog.addWindowListener
(new WindowAdapter() {
               
public void windowClosing(WindowEvent e) {
                     
// Remove the previous highlight (if any) when the dialog is being closed
                     
textArea.getHighlighter().removeAllHighlights();

                     
// Select the current match found (if any)
                     
if(indexOfMatchFound >= 0){
                           
int lastCaretPosition = textArea.getCaretPosition();
                            textArea.setCaretPosition
(indexOfMatchFound);
                            textArea.moveCaretPosition
(lastCaretPosition);
                            textArea.requestFocus
();
                     
}
                }
          })
;
   
}


   
private void init() {
         
try{
               
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
         
}
         
catch(Exception e){
               
e.printStackTrace();
         
}
         
setTitle("Untitled");
          setSize
(700, 400);
          setLocationRelativeTo
(null);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new TextAreas();
               
}
          })
;
   
}
}


You are here :  JavaPerspective.com  >   Advanced Tutorials  >   1. Advanced GUI Features  >   1.5. Text areas
Next tutorial :  JavaPerspective.com  >   Advanced Tutorials  >   1. Advanced GUI Features  >   1.6. Splash screens

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7