Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java Language
Expertise: Beginner
Dec 8, 1997



Application Security Testing: An Integral Part of DevOps

Text area & cursor control

Hi, I am looking for a way of displaying a textarea box and then being able to tell what text the user has highlighted (with mouse) and then replacing the text? Can this even be done with a applet?

The java.awt.TextComponent class (from which TextArea is derived), has three methods to retrieve mouse selection information. The getSelectedText() method will return a String containing the selected text, and the getSelectionStart() and getSelectionEnd() methods will return the start and end positions of the selected text. If getSelected() returns null, then no text is selected. The TextArea component provides a method called replaceRange() (formerly replaceText() in JDK 1.0.2) with which you can replace the contents of part of the TextArea. The following example shows you how to use these methods to erase the text selection on the click of a button:

This example is an applicatoin, but you can use the same technique in an applet.

import java.awt.*;
import java.awt.event.*;

public final class ReplaceText extends Frame {
  private TextArea __textArea;
  private Button __button;

  private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      int start, end;
      String selection;

      synchronized(__textArea) {
	selection = __textArea.getSelectedText();
	if(selection == null)
	start = __textArea.getSelectionStart();
	end   = __textArea.getSelectionEnd();
	__textArea.replaceRange("", start, end);

  public ReplaceText() {
    setLayout(new BorderLayout());
    __textArea = new TextArea("This is some sample text", 10, 40);
    __button   = new Button("Erase Selection");
    __button.addActionListener(new ButtonListener());
    add(__textArea, "Center");
    add(__button, "South");

  public static final void main(String[] args) {
    ReplaceText example;
    WindowListener exitListener;

    exitListener = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        Window window;
        window = e.getWindow();

    example = new ReplaceText();
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date