Text area & cursor control

Text area & cursor control

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

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

This example is an applicatoin, but youcan 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();;  }}


Share the Post: