Using replaceText with MenuItems

Question:
I created a UI for a selector guide using Frame, Menubar andMenuItems. I am having trouble writing the event handling; specifically, Ineed to see an example using replaceText when one chooses a menu item. Ihave no problem using textArea with a single string, but I can’t seem tofind my way with multiple text strings.

Answer:
The following example demonstrates how to use replaceText with menuitems. Let’s say you wanted a menuitem that duplicated the currently selected textin a text area. The TextDoubler class shown below does that by creating textArea and a menubar containing one menu item for doubling the currentlyselected text. It extends class Frame and overrides its action method tohandle menuitem events.

Note that it is not sufficient to just instantiate class Frame directlybecause the event handler for a frame throw away the events it gets. Youhave to subclass Frame and override the action or handleEvent routines toget it to do anything useful.

import java.awt.*;import java.io.*;public class TextDoubler extends Frame {        TextArea textarea;        public TextDoubler() {                // create a menubar with one menuitem for doubling the selected text.                MenuBar menubar = new MenuBar();                Menu menu = new Menu(“Doubler”);                MenuItem menuitem = new MenuItem(“Double text”);                menu.add(menuitem);                menubar.add(menu);                setMenuBar(menubar);                textarea = new TextArea(10, 40);                setLayout(new BorderLayout());                add(“South”, textarea);                pack();                show();        }        public boolean action(Event e, Object arg) {                if (e.target instanceof MenuItem &&                        e.id == Event.ACTION_EVENT ) {                        // grab the currently selected text and                        // insert two copies of it in place.                        // the selection can span multiple lines                        textarea.replaceText(textarea.getSelectedText() +                                                textarea.getSelectedText(),                                                textarea.getSelectionStart(),                                                textarea.getSelectionEnd());                        return true;                }                return false;        }        public static void main(String argv[]) {                TextDoubler t = new TextDoubler();                t.show();        }}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: