Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

How to perform clipboard operations on textbox in Java ME

From Wiki
Jump to: navigation, search
Article Metadata
Created: sparkystar (20 Dec 2007)
Last edited: hamishwillee (19 Nov 2013)

The following example adds copy and paste (clipboard) operations to a TextBox component.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SimpleClipBoard extends MIDlet implements CommandListener {
private Display display; // Reference to Display object
private TextBox tbClip; // Main textbox
private Command cmExit; // Command to exit
private Command cmStartMark; // Command to start marking a block
private Command cmCopy; // Command to copy to clipboard
private Command cmPaste; // Command to paste into textbox
private int beginOffset = 0; // The start index of copy
private char[] clipBoard = null; // The clipboard
private int clipBoardChars = 0; // Number of chars in clipboard
public SimpleClipBoard() {
display = Display.getDisplay(this);
// Create the Commands. Notice the priorities assigned
cmExit = new Command("Exit", Command.EXIT, 1);
cmStartMark = new Command("Mark", Command.SCREEN, 2);
cmCopy = new Command("Copy", Command.SCREEN, 3);
cmPaste = new Command("Paste", Command.SCREEN, 4);
tbClip = new TextBox("Clip Board", "Tee to grn", 15, TextField.ANY);
// Allocate a clipboard big enough to hold the entire textbox
clipBoard = new char[tbClip.getMaxSize()];
public void startApp() {
public void pauseApp() {
public void destroyApp(boolean unconditional) {
public void commandAction(Command c, Displayable s) {
if (c == cmStartMark) {
beginOffset = tbClip.getCaretPosition();
} else if (c == cmCopy && (tbClip.getCaretPosition() > beginOffset)) {
// Allocate an array to hold the current textbox contents
char[] chr = new char[tbClip.size()];
// Get the current textbox contents
// The count of characters in the clipboard
clipBoardChars = tbClip.getCaretPosition() - beginOffset;
// Copy the text into the clipboard
// arraycopy(source, sourceindex, dest, destindex, count)
System.arraycopy(chr, beginOffset, clipBoard, 0, clipBoardChars);
} else if (c == cmPaste) {
// Make sure the paste will not overrun the textbox length.
if ((tbClip.size() + clipBoardChars) <= tbClip.getMaxSize())
tbClip.insert(clipBoard, 0, clipBoardChars, tbClip.getCaretPosition());
} else if (c == cmExit) {
This page was last modified on 19 November 2013, at 23:31.
47 page views in the last 30 days.