Using replaceText with MenuItems

Using replaceText with MenuItems

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.

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*;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 ( instanceof MenuItem &&               == 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();      ;        }}


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist