FileDocCategorySizeDatePackage
Display.javaAPI DocJ2ME MIDP 2.0112071Thu Nov 07 12:02:26 GMT 2002javax.microedition.lcdui

Display

public class Display extends Object
Display represents the manager of the display and input devices of the system. It includes methods for retrieving properties of the device and for requesting that objects be displayed on the device. Other methods that deal with device attributes are primarily used with {@link Canvas Canvas} objects and are thus defined there instead of here.

There is exactly one instance of Display per {@link javax.microedition.midlet.MIDlet MIDlet} and the application can get a reference to that instance by calling the {@link #getDisplay(javax.microedition.midlet.MIDlet) getDisplay()} method. The application may call the getDisplay() method at any time during course of its execution. The Display object returned by all calls to getDisplay() will remain the same during this time.

A typical application will perform the following actions in response to calls to its MIDlet methods:

  • startApp - the application is moving from the paused state to the active state. Initialization of objects needed while the application is active should be done. The application may call {@link #setCurrent(Displayable) setCurrent()} for the first screen if that has not already been done. Note that startApp() can be called several times if pauseApp() has been called in between. This means that one-time initialization should not take place here but instead should occur within the MIDlet's constructor.
  • pauseApp - the application may pause its threads. Also, if it is desirable to start with another screen when the application is re-activated, the new screen should be set with setCurrent().
  • destroyApp - the application should free resources, terminate threads, etc. The behavior of method calls on user interface objects after destroyApp() has returned is undefined.

The user interface objects that are shown on the display device are contained within a {@link Displayable Displayable} object. At any time the application may have at most one Displayable object that it intends to be shown on the display device and through which user interaction occurs. This Displayable is referred to as the current Displayable.

The Display class has a {@link #setCurrent(Displayable) setCurrent()} method for setting the current Displayable and a {@link #getCurrent() getCurrent()} method for retrieving the current Displayable. The application has control over its current Displayable and may call setCurrent() at any time. Typically, the application will change the current Displayable in response to some user action. This is not always the case, however. Another thread may change the current Displayable in response to some other stimulus. The current Displayable will also be changed when the timer for an {@link Alert Alert} elapses.

The application's current Displayable may not physically be drawn on the screen, nor will user events (such as keystrokes) that occur necessarily be directed to the current Displayable. This may occur because of the presence of other MIDlet applications running simultaneously on the same device.

An application is said to be in the foreground if its current Displayable is actually visible on the display device and if user input device events will be delivered to it. If the application is not in the foreground, it lacks access to both the display and input devices, and it is said to be in the background. The policy for allocation of these devices to different MIDlet applications is outside the scope of this specification and is under the control of an external agent referred to as the application management software.

As mentioned above, the application still has a notion of its current Displayable even if it is in the background. The current Displayable is significant, even for background applications, because the current Displayable is always the one that will be shown the next time the application is brought into the foreground. The application can determine whether a Displayable is actually visible on the display by calling {@link Displayable#isShown isShown()}. In the case of Canvas, the {@link Canvas#showNotify() showNotify()} and {@link Canvas#hideNotify() hideNotify()} methods are called when the Canvas is made visible and is hidden, respectively.

Each MIDlet application has its own current Displayable. This means that the {@link #getCurrent() getCurrent()} method returns the MIDlet's current Displayable, regardless of the MIDlet's foreground/background state. For example, suppose a MIDlet running in the foreground has current Displayable F, and a MIDlet running in the background has current Displayable B. When the foreground MIDlet calls getCurrent(), it will return F, and when the background MIDlet calls getCurrent(), it will return B. Furthermore, if either MIDlet changes its current Displayable by calling setCurrent(), this will not affect the any other MIDlet's current Displayable.

It is possible for getCurrent() to return null. This may occur at startup time, before the MIDlet application has called setCurrent() on its first screen. The getCurrent() method will never return a reference to a Displayable object that was not passed in a prior call to setCurrent() call by this MIDlet.

System Screens

Typically, the current screen of the foreground MIDlet will be visible on the display. However, under certain circumstances, the system may create a screen that temporarily obscures the application's current screen. These screens are referred to as system screens. This may occur if the system needs to show a menu of commands or if the system requires the user to edit text on a separate screen instead of within a text field inside a Form. Even though the system screen obscures the application's screen, the notion of the current screen does not change. In particular, while a system screen is visible, a call to getCurrent() will return the application's current screen, not the system screen. The value returned by isShown() is false while the current Displayable is obscured by a system screen.

If system screen obscures a canvas, its hideNotify() method is called. When the system screen is removed, restoring the canvas, its showNotify() method and then its paint() method are called. If the system screen was used by the user to issue a command, the commandAction() method is called after showNotify() is called.

This class contains methods to retrieve the prevailing foreground and background colors of the high-level user interface. These methods are useful for creating CustomItem objects that match the user interface of other items and for creating user interfaces within Canvas that match the user interface of the rest of the system. Implementations are not restricted to using foreground and background colors in their user interfaces (for example, they might use highlight and shadow colors for a beveling effect) but the colors returned are those that match reasonably well with the implementation's color scheme. An application implementing a custom item should use the background color to clear its region and then paint text and geometric graphics (lines, arcs, rectangles) in the foreground color.

since
MIDP 1.0

Fields Summary
public static final int
LIST_ELEMENT
Image type for List element image.

The value of LIST_ELEMENT is 1.

public static final int
CHOICE_GROUP_ELEMENT
Image type for ChoiceGroup element image.

The value of CHOICE_GROUP_ELEMENT is 2.

public static final int
ALERT
Image type for Alert image.

The value of ALERT is 3.

public static final int
COLOR_BACKGROUND
A color specifier for use with getColor. COLOR_BACKGROUND specifies the background color of the screen. The background color will always contrast with the foreground color.

COLOR_BACKGROUND has the value 0.

public static final int
COLOR_FOREGROUND
A color specifier for use with getColor. COLOR_FOREGROUND specifies the foreground color, for text characters and simple graphics on the screen. Static text or user-editable text should be drawn with the foreground color. The foreground color will always constrast with background color.

COLOR_FOREGROUND has the value 1.

public static final int
COLOR_HIGHLIGHTED_BACKGROUND
A color specifier for use with getColor. COLOR_HIGHLIGHTED_BACKGROUND identifies the color for the focus, or focus highlight, when it is drawn as a filled in rectangle. The highlighted background will always constrast with the highlighted foreground.

COLOR_HIGHLIGHTED_BACKGROUND has the value 2.

public static final int
COLOR_HIGHLIGHTED_FOREGROUND
A color specifier for use with getColor. COLOR_HIGHLIGHTED_FOREGROUND identifies the color for text characters and simple graphics when they are highlighted. Highlighted foreground is the color to be used to draw the highlighted text and graphics against the highlighted background. The highlighted foreground will always constrast with the highlighted background.

COLOR_HIGHLIGHTED_FOREGROUND has the value 3.

public static final int
COLOR_BORDER
A color specifier for use with getColor. COLOR_BORDER identifies the color for boxes and borders when the object is to be drawn in a non-highlighted state. The border color is intended to be used with the background color and will contrast with it. The application should draw its borders using the stroke style returned by getBorderStyle().

COLOR_BORDER has the value 4.

public static final int
COLOR_HIGHLIGHTED_BORDER
A color specifier for use with getColor. COLOR_HIGHLIGHTED_BORDER identifies the color for boxes and borders when the object is to be drawn in a highlighted state. The highlighted border color is intended to be used with the background color (not the highlighted background color) and will contrast with it. The application should draw its borders using the stroke style returned by getBorderStyle().

COLOR_HIGHLIGHTED_BORDER has the value 5.

static final Object
LCDUILock
Static lock object for LCDUI package
static final Object
calloutLock
Static lock object for making calls into application code
static final int
WIDTH
horizontal width
static final int
HEIGHT
vertical height
static final int
ADORNEDHEIGHT
height available to draw on in normal mode
static final int
ERASE_COLOR
background color for erasing
static final int
BORDER_COLOR
border color for non-highlighted border
static final int
BORDER_H_COLOR
border color for highlighted border
static final int
DISPLAY_DEPTH
pixel depth of display.
static final boolean
DISPLAY_IS_COLOR
true, if display supports color.
static final boolean
POINTER_SUPPORTED
true, if the device has a pointing device.
static final boolean
MOTION_SUPPORTED
true, if motion events are supported.
static final boolean
REPEAT_SUPPORTED
true, if repeating events are supported.
static final boolean
IS_DOUBLE_BUFFERED
true, if the display is double buffered.
static final int
FG_COLOR
Standard foreground color
static final int
BG_H_COLOR
Standard background highlight color
static final int
FG_H_COLOR
Standard foreground highlight color
static final int
ALPHA_LEVELS
number of alpha levels supported
static final int
KEYCODE_UP
keyCode for up arrow
static final int
KEYCODE_DOWN
keyCode for down arrow
static final int
KEYCODE_LEFT
keyCode for left arrow
static final int
KEYCODE_RIGHT
keyCode for right arrow
static final int
KEYCODE_SELECT
keyCode for select
private static DisplayManagerImpl
displayManagerImpl
Display manager with private methods.
private static DisplayDeviceAccess
deviceAccess
Device Access manager.
private static EventHandler
eventHandler
event handler for this Display instance.
private static final Graphics
screenGraphics
singleton Graphics object
private DisplayAccessor
accessor
display accessor helper class
private javax.microedition.midlet.MIDlet
midlet
MIDlet for this display
private Displayable
current
current displayable instance
private boolean
wantsForeground
true, if last setCurrent was non-null
private int
stickyKeyMask
stores key code of the current key pressed at least once
private int
currentKeyMask
stores key code of the current key is currently down
private MIDletEventListener
midletEventListener
What gets the MIDlet level events.
private boolean
paintSuspended
true, if painting operations are suspended.
private boolean
hasForeground
true, if the Display is the foreground object.
private static Vector
queue1
first queue of serialized repaint operations.
private static Vector
queue2
second queue of serialized repaint operations.
private static Vector
currentQueue
current active queue for serially repainted operations.
private static SecurityToken
classSecurityToken
This class has a different security domain than the MIDlet suite
Constructors Summary
Display(javax.microedition.midlet.MIDlet m)
initializes the display with an accessor helper class.

param
m MIDlet that owns this display, can be null


/*
 * ************* Static initializer, constructor
 */
     

        /* done this way because native access to static fields is hard */
        DeviceCaps c = new DeviceCaps();

        WIDTH               = c.width;
        HEIGHT              = c.height;
        ADORNEDHEIGHT       = c.adornedHeight;
        ERASE_COLOR         = c.eraseColor;
        DISPLAY_DEPTH       = c.displayDepth;
        DISPLAY_IS_COLOR    = c.displayIsColor;
        POINTER_SUPPORTED   = c.pointerSupported;
        MOTION_SUPPORTED    = c.motionSupported;
        REPEAT_SUPPORTED    = c.repeatSupported;
        IS_DOUBLE_BUFFERED  = c.isDoubleBuffered;
        FG_COLOR            = 0;
        BG_H_COLOR          = FG_COLOR;
        FG_H_COLOR          = ERASE_COLOR;

        Text.FG_COLOR       = FG_COLOR;
        Text.FG_H_COLOR     = FG_H_COLOR;

        ALPHA_LEVELS        = c.numAlphaLevels;

        KEYCODE_UP          = c.keyCodeUp;
        KEYCODE_DOWN        = c.keyCodeDown;
        KEYCODE_LEFT        = c.keyCodeLeft;
        KEYCODE_RIGHT       = c.keyCodeRight;
        KEYCODE_SELECT      = c.keyCodeSelect;

        c = null; // let the DeviceCaps instance be garbage collected

        /* Let com.sun.midp classes call in to this class. */
        displayManagerImpl = new DisplayManagerImpl();
        DisplayManagerFactory.SetDisplayManagerImpl(displayManagerImpl);
        deviceAccess = new DisplayDeviceAccess();
        eventHandler = getEventHandler();

        screenGraphics = Graphics.getGraphics(null);
    
        midlet = m;
        accessor = new DisplayAccessor();
        drawTrustedIcon(false);
    
Methods Summary
private voidcallInvalidate(Item item)
Invalidate the current Form possibly due to an item's request

param
item the Item which caused the invalidation

        Displayable currentCopy = current;

        if (currentCopy != null) {
            currentCopy.callInvalidate(item);
        }
    
private voidcallItemStateChanged(Item item)
Notify an ItemStateChangeListener of a change in the given item.

param
item the Item which has changed

        Displayable currentCopy = current;

        if (currentCopy != null) {
            currentCopy.callItemStateChanged(item);
        }
    
public voidcallSerially(java.lang.Runnable r)
Causes the Runnable object r to have its run() method called later, serialized with the event stream, soon after completion of the repaint cycle. As noted in the Event Handling section of the package summary, the methods that deliver event notifications to the application are all called serially. The call to r.run() will be serialized along with the event calls into the application. The run() method will be called exactly once for each call to callSerially(). Calls to run() will occur in the order in which they were requested by calls to callSerially().

If the current Displayable is a Canvas that has a repaint pending at the time of a call to callSerially(), the paint() method of the Canvas will be called and will return, and a buffer switch will occur (if double buffering is in effect), before the run() method of the Runnable is called. If the current Displayable contains one or more CustomItems that have repaints pending at the time of a call to callSerially(), the paint() methods of the CustomItems will be called and will return before the run() method of the Runnable is called. Calls to the run() method will occur in a timely fashion, but they are not guaranteed to occur immediately after the repaint cycle finishes, or even before the next event is delivered.

The callSerially() method may be called from any thread. The call to the run() method will occur independently of the call to callSerially(). In particular, callSerially() will never block waiting for r.run() to return.

As with other callbacks, the call to r.run() must return quickly. If it is necessary to perform a long-running operation, it may be initiated from within the run() method. The operation itself should be performed within another thread, allowing run() to return.

The callSerially() facility may be used by applications to run an animation that is properly synchronized with the repaint cycle. A typical application will set up a frame to be displayed and then call repaint(). The application must then wait until the frame is actually displayed, after which the setup for the next frame may occur. The call to run() notifies the application that the previous frame has finished painting. The example below shows callSerially() being used for this purpose.


class Animation extends Canvas
implements Runnable {

// paint the current frame
void paint(Graphics g) { ... }

Display display; // the display for the application

void paint(Graphics g) { ... } // paint the current frame

void startAnimation() {
// set up initial frame
repaint();
display.callSerially(this);
}

// called after previous repaint is finished
void run() {
if ( /* there are more frames */ ) {
// set up the next frame
repaint();
display.callSerially(this);
}
}
} 

param
r instance of interface Runnable to be called

        if (r == null) {
            throw new NullPointerException();
        }
        synchronized (LCDUILock) {
            currentQueue.addElement(r);
            eventHandler.scheduleCallSerially();
        }
    
voidclearAlert(Displayable returnScreen)
Called by Alert when a modal alert has exited.

param
returnScreen The Displayable to return to after this Alert is cleared.

        eventHandler.scheduleScreenChange(this, returnScreen);
    
private native voiddrawTrustedIcon(boolean drawTrusted)
Control the drawing of the trusted MIDlet icon in native.

param
drawTrusted true if the icon should be drawn, false if it should not.

public booleanflashBacklight(int duration)
Requests a flashing effect for the device's backlight. The flashing effect is intended to be used to attract the user's attention or as a special effect for games. Examples of flashing are cycling the backlight on and off or from dim to bright repeatedly. The return value indicates if the flashing of the backlight can be controlled by the application.

The flashing effect occurs for the requested duration, or it is switched off if the requested duration is zero. This method returns immediately; that is, it must not block the caller while the flashing effect is running.

Calls to this method are honored only if the Display is in the foreground. This method MUST perform no action and return false if the Display is in the background.

The device MAY limit or override the duration. For devices that do not include a controllable backlight, calls to this method return false.

param
duration the number of milliseconds the backlight should be flashed, or zero if the flashing should be stopped
return
true if the backlight can be controlled by the application and this display is in the foreground, false otherwise
throws
IllegalArgumentException if duration is negative
since
MIDP 2.0


        if (!hasForeground) {
            return false;
        }

        return deviceAccess.flashBacklight(duration);
    
public intgetBestImageHeight(int imageType)
Returns the best image height for a given image type. The image type must be one of {@link #LIST_ELEMENT}, {@link #CHOICE_GROUP_ELEMENT}, or {@link #ALERT}.

param
imageType the image type
return
the best image height for the image type, may be zero if there is no best size; must not be negative
throws
IllegalArgumentException if imageType is illegal
since
MIDP 2.0

        switch (imageType) {
        case LIST_ELEMENT:
        case CHOICE_GROUP_ELEMENT:
            return ChoiceGroup.PREFERRED_IMG_H;
        case ALERT:
            // return max height ignoring title and ticker and
            // allow for 2 lines of Text to be visible without scrolling
            return Display.ADORNEDHEIGHT - 2 * Screen.CONTENT_HEIGHT;
        default:
            throw new IllegalArgumentException();
        }
    
public intgetBestImageWidth(int imageType)
Returns the best image width for a given image type. The image type must be one of {@link #LIST_ELEMENT}, {@link #CHOICE_GROUP_ELEMENT}, or {@link #ALERT}.

param
imageType the image type
return
the best image width for the image type, may be zero if there is no best size; must not be negative
throws
IllegalArgumentException if imageType is illegal
since
MIDP 2.0

        switch (imageType) {
        case LIST_ELEMENT:
        case CHOICE_GROUP_ELEMENT:
            return ChoiceGroup.PREFERRED_IMG_W;
        case ALERT:
            return Display.WIDTH;
        default:
            throw new IllegalArgumentException();
        }
    
public intgetBorderStyle(boolean highlighted)
Returns the stroke style used for border drawing depending on the state of the component (highlighted/non-highlighted). For example, on a monochrome system, the border around a non-highlighted item might be drawn with a DOTTED stroke style while the border around a highlighted item might be drawn with a SOLID stroke style.

param
highlighted true if the border style being requested is for the highlighted state, false if the border style being requested is for the non-highlighted state
return
{@link Graphics#DOTTED} or {@link Graphics#SOLID}
since
MIDP 2.0

        return (highlighted == true ? Graphics.SOLID : Graphics.DOTTED);
    
private voidgetCallSerially()
run the serially repainted operations.

        java.util.Vector q = null;

        synchronized (LCDUILock) {
            q = currentQueue;
            currentQueue = (q == queue1) ? queue2 : queue1;
        }

        // SYNC NOTE: we synch on calloutLock for the call into
        // application code
        synchronized (calloutLock) {
            for (int i = 0; i < q.size(); i++) {
                try {
                    Runnable r = (Runnable) q.elementAt(i);
                    r.run();
                } catch (Throwable thr) {
                    handleThrowable(thr);
                }
            }
        }

        q.removeAllElements();
    
public intgetColor(int colorSpecifier)
Returns one of the colors from the high level user interface color scheme, in the form 0x00RRGGBB based on the colorSpecifier passed in.

param
colorSpecifier the predefined color specifier; must be one of {@link #COLOR_BACKGROUND}, {@link #COLOR_FOREGROUND}, {@link #COLOR_HIGHLIGHTED_BACKGROUND}, {@link #COLOR_HIGHLIGHTED_FOREGROUND}, {@link #COLOR_BORDER}, or {@link #COLOR_HIGHLIGHTED_BORDER}
return
color in the form of 0x00RRGGBB
throws
IllegalArgumentException if colorSpecifier is not a valid color specifier
since
MIDP 2.0

        switch (colorSpecifier) {
        case COLOR_BACKGROUND:
            return ERASE_COLOR;
        case COLOR_FOREGROUND:
            return FG_COLOR;
        case COLOR_HIGHLIGHTED_BACKGROUND:
            return BG_H_COLOR;
        case COLOR_HIGHLIGHTED_FOREGROUND:
            return FG_H_COLOR;
        // REMINDER: COLOR_BORDER color and
        // COLOR_HIGHLIGHTED_BORDER color will
        // be changed once HI input is avaiable.
        case COLOR_BORDER:
            return BORDER_COLOR;
        case COLOR_HIGHLIGHTED_BORDER:
            return BORDER_H_COLOR;
        default:
            throw new IllegalArgumentException();
        }
    
public DisplayablegetCurrent()
Gets the current Displayable object for this MIDlet. The Displayable object returned may not actually be visible on the display if the MIDlet is running in the background, or if the Displayable is obscured by a system screen. The {@link Displayable#isShown() Displayable.isShown()} method may be called to determine whether the Displayable is actually visible on the display.

The value returned by getCurrent() may be null. This occurs after the application has been initialized but before the first call to setCurrent().

return
the MIDlet's current Displayable object
see
#setCurrent

        return current;
    
public static javax.microedition.lcdui.DisplaygetDisplay(javax.microedition.midlet.MIDlet m)
Gets the Display object that is unique to this MIDlet.

param
m MIDlet of the application
return
the display object that application can use for its user interface
throws
NullPointerException if m is null

        MIDletState ms;
        Display d;

        synchronized (LCDUILock) {
            // Find or create if necessary the Display
            ms = MIDletStateMap.getState(m);
            if (ms != null) {
                d = ms.getDisplay();
                if (d != null) {
                    return d;
                }
            }

            throw new
                IllegalStateException("No display created for given MIDlet");
        }
    
private static EventHandlergetEventHandler()
get the class that handle I/O event stream for this display.

return
handle to the event handler for this display


        String n = Configuration.getProperty(
            "com.sun.midp.lcdui.eventHandler");

        try {
            return (EventHandler) (Class.forName(n)).newInstance();
        } catch (Exception e) { }

        if (Configuration.getProperty("microedition.configuration") != null) {
            try {
                return (EventHandler) (Class.forName(
                    "com.sun.midp.lcdui.AutomatedEventHandler")).newInstance();
            } catch (Exception e) { }

            try {
                return (EventHandler) (Class.forName(
                    "com.sun.midp.lcdui.DefaultEventHandler")).newInstance();
            } catch (Exception e) { }

            throw new Error("Unable to establish EventHandler");
        }

        try {
            return (EventHandler)
                (Class.forName(
                    "com.sun.midp.lcdui.AWTEventHandler")).newInstance();
        } catch (Exception e) { }

        throw new Error("Unable to establish EventHandler");
    
static intgetGameAction(int keyCode)
Return the game action associated with the given key code on the device. keyCode must refer to a key that is mapped as a game key on the device The game action of the key is returned. The return value will be 0 if the key is not mapped to a game action or not present on the device.

param
keyCode the key code
return
the corresponding game action (UP, DOWN, LEFT, RIGHT, FIRE, etc.)

        return eventHandler.getGameAction(keyCode);
    
static intgetKeyCode(int gameAction)
Return the key code that corresponds to the specified game action on the device. gameAction must be a defined game action (Canvas.UP, Canvas.DOWN, Canvas.FIRE, etc.) Post-conditions:
The key code of the key that corresponds to the specified action is returned. The return value will be -1 if the game action is invalid or not supported by the device.

param
gameAction The game action to obtain the key code for.
return
the key code.

        return eventHandler.getKeyCode(gameAction);
    
static java.lang.StringgetKeyName(int keyCode)
Gets an informative key string for a key. The string returned should resemble the text physically printed on the key. For example, on a device with function keys F1 through F4, calling this method on the keycode for the F1 key will return the string "F1". A typical use for this string will be to compose help text such as "Press F1 to proceed."

There is no direct mapping from game actions to key names. To get the string name for a game action, the application must call

getKeyName(getKeyCode(GAME_A))

param
keyCode the key code being requested
return
a string name for the key, or null if no name is available

        return eventHandler.getKeyName(keyCode);
    
javax.microedition.midlet.MIDletgetMIDlet()
get the associated MIDlet from the current display.

return
MIDlet that is associated with the current Display.

        return midlet;
    
static intgetSystemKey(int keyCode)
returns 0 if keyCode is not a system key. Otherwise, returns one of the EventHandler.SYSTEM_KEY_ constants.

param
keyCode get the system equivalent key.
return
translated system key or zero if it is not a system key.

        return eventHandler.getSystemKey(keyCode);
    
intgetVerticalScrollPosition()
get the current vertical scroll position.

return
the vertical scroll position.

        // SYNC NOTE: No need to lock here because 'current'
        // can only be null once, at startup, so we don't care
        // if 'current' changes values, just that it isn't null
        if (current != null) {
            return current.getVerticalScrollPosition();
        } else {
            return 0;
        }
    
intgetVerticalScrollProportion()
get the current vertical scroll proportion.

return
the vertical scroll proportion.

        // SYNC NOTE: No need to lock here because 'current'
        // can only be null once, at startup, so we don't care
        // if 'current' changes values, just that it isn't null
         if (current != null) {
            return current.getVerticalScrollProportion();
        } else {
            return 100;
        }
    
static voidhandleThrowable(java.lang.Throwable t)
This is a utility method used to handle any Throwables caught while calling application code. The default implementation will simply call printStackTrace() on the Throwable. Note, the parameter must be non-null or this method will generate a NullPointerException.

param
t The Throwable caught during the call into application code.

        t.printStackTrace();
    
private static voidinitSecurityToken(SecurityToken token)
Initializes the security token for this class, so it can perform actions that a normal MIDlet Suite cannot.

param
token security token for this class.

        if (classSecurityToken != null) {
            return;
        }
        
        classSecurityToken = token;
    
voidinvalidate(Item item)
Schedule a Form invalidation based on the given Item. The item may be null.

param
item The Item which caused the invalidation

        eventHandler.scheduleInvalidate(item);
    
public booleanisColor()
Gets information about color support of the device.

return
true if the display supports color, false otherwise

        return DISPLAY_IS_COLOR;
    
static booleanisGraphicsDisplay(Graphics gfx)
See if we're using the display's Graphics object.

param
gfx Graphics object to compare to screenGraphics.
return
true if gfx equals screenGraphics, false otherwise.

        return screenGraphics == gfx;
    
booleanisShown(Displayable d)
is the current display visible.

param
d displayble instance to check, if current and visible.
return
true, if the Display is visible and the object is current.

        // SYNC NOTE: calls to isShown() should be synchronized on
        // the LCDUILock.
        return hasForeground
            && !paintSuspended
            && (current == d);
    
voiditemStateChanged(Item item)
Schedule the notificaton of an ItemStateListener due to a change in the given item.

param
item The Item which has changed

        eventHandler.scheduleItemStateChanged(item);
    
private native intnVibrate(int dur)
Plays the vibration.

param
dur the duration in milli seconds
return
if it's successful, return 1, othewise return 0

public intnumAlphaLevels()
Gets the number of alpha transparency levels supported by this implementation. The minimum legal return value is 2, which indicates support for full transparency and full opacity and no blending. Return values greater than 2 indicate that alpha blending is supported. For further information, see Alpha Processing.

return
number of alpha levels supported
since
MIDP 2.0

        return ALPHA_LEVELS;
    
public intnumColors()
Gets the number of colors (if isColor() is true) or graylevels (if isColor() is false) that can be represented on the device.

Note that the number of colors for a black and white display is 2.

return
number of colors

        return (1 << DISPLAY_DEPTH);
    
booleanplayAlertSound(AlertType t)
play a sound.

param
t type of alert
return
true, if sound was played.


        if (!paintSuspended && hasForeground) {
            try {
                // SYNC NOTE: playAlertSound is a native method, no locking
                // necessary
                return playAlertSound(t.getType());
            } catch (Exception e) {}
        }

        return false;
    
private native booleanplayAlertSound(int alertType)
play a sound.

param
alertType type of alert
return
true, if sound was played.

private native voidrefresh(int x1, int y1, int x2, int y2)
redraw a portiion of the display.

param
x1 upper left corner x-coordinate
param
y1 upper left corner y-coordinate
param
x2 lower right corner x-coordinate
param
y2 lower right corner y-coordinat

private voidregisterNewCurrent(Displayable newCurrent, boolean fgChange)
Registers a new Displayable object to this Display. This means that it is now the current Displayable object, eligible to receive input events, and eligible to paint. If necessary, showNotify() is called on this Displayable and hideNotify() is called on the Displayable being replaced. This method is used to initialize a Displayable as a result of either: - a SCREEN change timerEvent() - a call to resumePainting() - a change in foreground status of this Display (results in a call to resumePainting())

param
newCurrent The Displayable to take effect as the new "current" Displayable
param
fgChange If True, then this call to registerNewCurrent() is a result of this Display being moved to the foreground, i.e. setForeground(true)

        // If this Display is not in the foreground, simply record
        // the new Displayable and return. When this Display resumes
        // the foreground, this method will be called again.

        Displayable currentCopy = null;

        // SYNC NOTE: The implementation of callShowNotify() will
        // use LCDUILock to lock around its internal handling.
        // Canvas will override callShowNotify() to first call
        // super(), and then obtain a lock
        // on calloutLock around a call to the applications
        // showNotify() method.

        if (newCurrent != null) {
            newCurrent.callShowNotify(Display.this);
        }

        synchronized (LCDUILock) {
            if (fgChange) {
                hasForeground = true;

                if (newCurrent == null) {
                    /*
                     * At least clear the screen so the last display, which
                     * could be destroyed (like the Selector) is not still
                     * showing.
                     */
                    screenGraphics.reset(0, 0, WIDTH, HEIGHT);
                    screenGraphics.setColor(Display.ERASE_COLOR);
                    screenGraphics.fillRect(0, 0, WIDTH, HEIGHT);
                    refresh(0, 0, WIDTH, HEIGHT);
                    eventHandler.updateCommandSet(null, 0, null, 0);

                    /*
                     * Without a displayable, we can shortcircuit the rest
                     * of the call and simply return.
                     */
                    return;
                }
            }


            // This will suppress drags, repeats and ups until a
            // corresponding down is seen.
            accessor.sawPointerPress = accessor.sawKeyPress = false;

            // We re-set our suspended state to false.
            paintSuspended = false;

            // We make a copy of the current Displayable to call
            // hideNotify() when we're done
            currentCopy = current;

            current = newCurrent;

            // set mapping between GameCanvas and DisplayAccess
            // set Game key event flag based on value passed in
            // GameCanvas constructor.
            if (current instanceof GameCanvas) {
                GameMap.register(current, accessor);
                stickyKeyMask = currentKeyMask = 0;
            } else {
                // set the keymask to -1 when
                // the displayable is not a GameCanvas.
                stickyKeyMask = currentKeyMask = -1;
            }

            setVerticalScroll(
                current.getVerticalScrollPosition(),
                current.getVerticalScrollProportion());

            // Next, update the command set
                updateCommandSet();

        } // synchronized

        // SYNC NOTE: The implementation of callHideNotify()
        // will use LCDUILock to lock around its internal handling.
        // Canvas will override callHideNotify(), first calling
        // super(), and then obtaining calloutLock around a call
        // to the application's hideNotify() method.

        // NOTE: the reason we test for currentCopy != current is
        // for cases when the Display has interrupted its suspension
        // by a system screen to immediately return to its "current"
        // Displayable. In this case, currentCopy == current, and
        // we've just called showNotify() above (no need to call
        // hideNotify())

        if (currentCopy != null && currentCopy != current) {
            currentCopy.callHideNotify(Display.this);
        }
        repaint(0, 0, WIDTH, HEIGHT, null);
    
voidrepaint(int x1, int y1, int x2, int y2, java.lang.Object target)
Process the specified repaint request immediately.

param
x1 The x origin of the paint bounds
param
y1 The y origin of the paint bounds
param
x2 The x coordinate of the lower right bounds
param
y2 The y coordinate of the lower right bounds
param
target The optional paint target SYNC NOTE: this method performs its own locking of LCDUILock and calloutLock. Therefore, callers must not hold any locks when they call this method.

        Displayable currentCopy = null;

        synchronized (LCDUILock) {
            if (paintSuspended || !hasForeground) {
                return;
            }
            currentCopy = current;
        }

        if (currentCopy == null) {
            return;
        }

        screenGraphics.reset(x1, y1, x2, y2);
        current.callPaint(screenGraphics, target);
        refresh(x1, y1, x2, y2);
    
voidrepaintImpl(Displayable d, int x, int y, int w, int h, java.lang.Object target)
Request a repaint for the given Displayable. The rectangle to be painted is in x,y,w,h. If delay is greater than zero, the repaint may be deferred until that interval (in milliseconds) has elapsed. If the given Displayable is not current, the request is ignored. This is safe because whenever a Displayable becomes current, it gets a full repaint anyway. The target Object is optional. It will be packaged along with the repaint request and arrive later when the repaint is serviced in the callPaint() routine - IF this paint request has not been coalesced with other repaints.

param
d displayable object to be drawn
param
x upper left corner x-coordinate
param
y upper left corner y-coordinate
param
w horizontal width
param
h vertical height
param
target an optional paint target


        synchronized (LCDUILock) {
            if (paintSuspended || !hasForeground || d != current) {
                return;
            }
        }

        eventHandler.scheduleRepaint(x, y, w, h, target);
    
voidscreenChange(Displayable d)
Change the current screen to the given displayable.

param
d The Displayable to make current

        synchronized (LCDUILock) {
            if (current == d && !paintSuspended) {
                return;
            } else if (paintSuspended) {
                // If we happen to be suspended, simply update our current
                // screen to be the new Displayable and return. When we are
                // resumed, registerNewCurrent() will be called with the
                // newly set screen
                current = d;
                return;
            }
        }

        // Its ok to ignore the foreground/paintSuspended state from here
        // on, the last thing registerNewCurrent() will do is try to do
        // a repaint(), which will not occur if the
        // foreground/paintSuspended status has changed in the meantime.
        registerNewCurrent(d, false);
    
voidserviceRepaints(Displayable d)
Process any pending repaint requests immediately.

param
d The Displayable which is requesting the repaint (Used to determine if the Displayable making the request is currently being shown) SYNC NOTE: this method performs its own locking of LCDUILock. Therefore, callers must not hold any locks when they call this method.


        synchronized (LCDUILock) {
            if (paintSuspended || !hasForeground || d != current) {
                return;
            }
        }

        eventHandler.serviceRepaints();
    
public voidsetCurrent(Alert alert, Displayable nextDisplayable)
Requests that this Alert be made current, and that nextDisplayable be made current after the Alert is dismissed. This call returns immediately regardless of the Alert's timeout value or whether it is a modal alert. The nextDisplayable must not be an Alert, and it must not be null.

The automatic advance to nextDisplayable occurs only when the Alert's default listener is present on the Alert when it is dismissed. See Alert Commands and Listeners for details.

In other respects, this method behaves identically to {@link #setCurrent(Displayable) setCurrent(Displayable)}.

param
alert the alert to be shown
param
nextDisplayable the Displayable to be shown after this alert is dismissed
throws
NullPointerException if alert or nextDisplayable is null
throws
IllegalArgumentException if nextDisplayable is an Alert
see
Alert
see
#getCurrent

        if ((alert == null) || (nextDisplayable == null)) {
            throw new NullPointerException();
        }

        if (nextDisplayable instanceof Alert) {
            throw new IllegalArgumentException();
        }

        synchronized (LCDUILock) {
            alert.setReturnScreen(nextDisplayable);
            setCurrentImpl(alert);
        }
    
public voidsetCurrent(Displayable nextDisplayable)
Requests that a different Displayable object be made visible on the display. The change will typically not take effect immediately. It may be delayed so that it occurs between event delivery method calls, although it is not guaranteed to occur before the next event delivery method is called. The setCurrent() method returns immediately, without waiting for the change to take place. Because of this delay, a call to getCurrent() shortly after a call to setCurrent() is unlikely to return the value passed to setCurrent().

Calls to setCurrent() are not queued. A delayed request made by a setCurrent() call may be superseded by a subsequent call to setCurrent(). For example, if screen S1 is current, then


d.setCurrent(S2);
d.setCurrent(S3); 

may eventually result in S3 being made current, bypassing S2 entirely.

When a MIDlet application is first started, there is no current Displayable object. It is the responsibility of the application to ensure that a Displayable is visible and can interact with the user at all times. Therefore, the application should always call setCurrent() as part of its initialization.

The application may pass null as the argument to setCurrent(). This does not have the effect of setting the current Displayable to null; instead, the current Displayable remains unchanged. However, the application management software may interpret this call as a request from the application that it is requesting to be placed into the background. Similarly, if the application is in the background, passing a non-null reference to setCurrent() may be interpreted by the application management software as a request that the application is requesting to be brought to the foreground. The request should be considered to be made even if the current Displayable is passed to the setCurrent(). For example, the code


d.setCurrent(d.getCurrent()); 

generally will have no effect other than requesting that the application be brought to the foreground. These are only requests, and there is no requirement that the application management software comply with these requests in a timely fashion if at all.

If the Displayable passed to setCurrent() is an {@link Alert Alert}, the previously current Displayable, if any, is restored after the Alert has been dismissed. If there is a current Displayable, the effect is as if setCurrent(Alert, getCurrent()) had been called. Note that this will result in an exception being thrown if the current Displayable is already an alert. If there is no current Displayable (which may occur at startup time) the implementation's previous state will be restored after the Alert has been dismissed. The automatic restoration of the previous Displayable or the previous state occurs only when the Alert's default listener is present on the Alert when it is dismissed. See Alert Commands and Listeners for details.

To specify the Displayable to be shown after an Alert is dismissed, the application should use the {@link #setCurrent(Alert,Displayable) setCurrent(Alert, Displayable)} method. If the application calls setCurrent() while an Alert is current, the Alert is removed from the display and any timer it may have set is cancelled.

If the application calls setCurrent() while a system screen is active, the effect may be delayed until after the system screen is dismissed. The implementation may choose to interpret setCurrent() in such a situation as a request to cancel the effect of the system screen, regardless of whether setCurrent() has been delayed.

param
nextDisplayable the Displayable requested to be made current; null is allowed
see
#getCurrent

        synchronized (LCDUILock) {
            if (nextDisplayable instanceof Alert) {
                /*
                 * This implicitly goes back to the current screen.
                 *
                 * If there is a pending screen change, we take that
                 * into account also.  This probably acts according to
                 * the principle of least astonishment.  Also, it
                 * has the effect of preventing an implicit call of
                 * setCurrent(Alert, Alert) because nextScreen is
                 * never an alert.
                 *
                 * REMIND: This is subject to spec interpretation;
                 * the handling of setCurrent(Alert) is a weak area.
                 */

                // NOTE: Removed the copy of the Alert
                ((Alert)nextDisplayable).setReturnScreen(current);
            }

            setCurrentImpl(nextDisplayable);
        } // synchronized
    
voidsetCurrentImpl(Displayable nextDisplayable)
Set the current Displayable and notify the display manager if the has current state has changed.

param
nextDisplayable The next Displayable to display

        boolean previousWantsForeground = wantsForeground;

        /*
         * note: this method handles the setCurrent(null) then
         * setCurrent(getCurrent()) case
         */

        wantsForeground = nextDisplayable != null;

        if (wantsForeground) {
            if (nextDisplayable != current) {
                if (hasForeground) {
                    // If a call to setCurrent() is coming in while in a
                    // suspended state, notify the event handler to dismiss
                    // the system screen
                    if (paintSuspended) {
                        eventHandler.clearSystemScreen();
                        paintSuspended = false;
                    }

                    eventHandler.scheduleScreenChange(this, nextDisplayable);

                    /*
                     * have the foreground, no need to notify the display
                     * manager
                     */
                    return;
                }

                // set current before we notify the display manager
                current = nextDisplayable;
            }
        }

        if (wantsForeground != previousWantsForeground) {
            // only notify the display manager on a change
            displayManagerImpl.notifyWantsForeground(this.accessor,
                                                     wantsForeground);
        }
    
public voidsetCurrentItem(Item item)
Requests that the Displayable that contains this Item be made current, scrolls the Displayable so that this Item is visible, and possibly assigns the focus to this Item. The containing Displayable is first made current as if {@link #setCurrent(Displayable) setCurrent(Displayable)} had been called. When the containing Displayable becomes current, or if it is already current, it is scrolled if necessary so that the requested Item is made visible. Then, if the implementation supports the notion of input focus, and if the Item accepts the input focus, the input focus is assigned to the Item.

This method always returns immediately, without waiting for the switching of the Displayable, the scrolling, and the assignment of input focus to take place.

It is an error for the Item not to be contained within a container. It is also an error if the Item is contained within an Alert.

param
item the item that should be made visible
throws
IllegalStateException if the item is not owned by a container
throws
IllegalStateException if the item is owned by an Alert
throws
NullPointerException if item is null
since
MIDP 2.0

        synchronized (LCDUILock) {

            Screen nextDisplayable = item.getOwner();
            if (nextDisplayable instanceof Form) {
                ((Form)nextDisplayable).setCurrentItem(item);
            }

            if (nextDisplayable == null) {
                throw new IllegalStateException();
            }

            setCurrentImpl(nextDisplayable);
        } // synchronized
    
native voidsetInputMode(int mode)
set the input, mode.

param
mode type of input to accept.

native voidsetVerticalScroll(int scrollPosition, int scrollProportion)
set the current vertical scroll position and proportion.

param
scrollPosition vertical scroll position.
param
scrollProportion vertical scroll proportion.

voidupdateCommandSet()
Update the system's account of abstract commands SYNC NOTE: Calls to this method should be synchronized on the LCDUILock


        Command[] screenCommands = current.getCommands();
        int screenComCount = current.getCommandCount();
        for (int i = 0; i < screenComCount; i++) {
             screenCommands[i].setInternalID(i);
        }

        Item curItem = current.getCurrentItem();
        if (curItem == null) {
            eventHandler.updateCommandSet(null, 0,
                                          screenCommands, screenComCount);
        } else {
            Command[] itemCommands = curItem.getCommands();
            int itemComCount = curItem.getCommandCount();
            for (int i = 0; i < itemComCount; i++) {
                itemCommands[i].setInternalID(i + screenComCount);
            }
            eventHandler.updateCommandSet(itemCommands, itemComCount,
                                          screenCommands, screenComCount);
        }
    
public booleanvibrate(int duration)
Requests operation of the device's vibrator. The vibrator is intended to be used to attract the user's attention or as a special effect for games. The return value indicates if the vibrator can be controlled by the application.

This method switches on the vibrator for the requested duration, or switches it off if the requested duration is zero. If this method is called while the vibrator is still activated from a previous call, the request is interpreted as setting a new duration. It is not interpreted as adding additional time to the original request. This method returns immediately; that is, it must not block the caller while the vibrator is running.

Calls to this method are honored only if the Display is in the foreground. This method MUST perform no action and return false if the Display is in the background.

The device MAY limit or override the duration. For devices that do not include a controllable vibrator, calls to this method return false.

param
duration the number of milliseconds the vibrator should be run, or zero if the vibrator should be turned off
return
true if the vibrator can be controlled by the application and this display is in the foreground, false otherwise
throws
IllegalArgumentException if duration is negative
since
MIDP 2.0


        if (!hasForeground) {
            return false;
        }

        if (duration < 0) {
            throw new IllegalArgumentException();
        }
        
        if (nVibrate(duration) <= 0) {
            return false;
        } else {
            return true;
        }