JTextArea Editing
Home ] Up ] JTextComponent ] JTextField ] JPasswordField ] JTextArea ] The Document Model ] JTextArea Scrolling ] [ JTextArea Editing ]

 

 

We can also explore editing text in a text area.

Here's an example, which is slightly modified from the earlier scrolling text area examples.:

package swingExamples;

import java.awt.BorderLayout;
import java.awt.Container;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;

class EditingTextAreasPanel extends JPanel
{
  public EditingTextAreasPanel()
  {
    setLayout(new BorderLayout());
    add( new TextAreaPanel(), BorderLayout.CENTER);
    add( new InputPanel(), BorderLayout.SOUTH);
  }
  
  /////// Private data /////
  private JTextArea m_textArea = new JTextArea(8, 40);
  private JButton m_replaceButton = new JButton("Replace");
  private JTextField m_fromField = new JTextField(5);
  private JTextField m_toField = new JTextField(5);
  
  /////// Inner classes /////
  class TextAreaPanel extends JPanel
  {
    public TextAreaPanel()
    {
      setLayout(new BorderLayout());
      m_textArea = new JTextArea(8, 40);
      m_textArea.setText(
          "The quick brown fox jumps over the lazy dog.");
      JScrollPane scrollPane = new JScrollPane(m_textArea);
      scrollPane.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      scrollPane.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      add(scrollPane, BorderLayout.CENTER);
    }
  }
  
  class InputPanel extends JPanel
  {
    public InputPanel()
    {
      
      add(m_replaceButton);
      m_replaceButton.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent ev)
          {
            String from = m_fromField.getText();
            int index = 
                m_textArea.getText().indexOf(from);
            if (index >= 0 && from.length() > 0)
            {
              m_textArea.replaceRange(
                  m_toField.getText(), index,
                  index + from.length());
            }
          }
        }
      );
      add(m_fromField);
      add(new JLabel("with"));
      add(m_toField);
    }
  }
}

class EditingTextAreasFrame extends JFrame
{
  public EditingTextAreasFrame()
  {
    setTitle("EditingTextAreas");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    contentPane.add( new EditingTextAreasPanel() );
  }
}

public class EditingTextAreas
{
  public static void main(String[] args)
  {
    EditingTextAreasFrame frame = 
                new EditingTextAreasFrame();
    frame.setVisible(true);
  }
}

which produces the following:

 

This page was last modified on 02 October, 2007