Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Text area & cursor control

Question:
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?

Answer:
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)
	  return;
	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);
    __textArea.setEditable(true);
    __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();
        window.setVisible(false);
        window.dispose();
        System.exit(0);
      }
    };                     

    example = new ReplaceText();
    example.addWindowListener(exitListener);
    example.pack();
    example.show();
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap