Java Reference
In-Depth Information
}
Figure 3.17. Output of the
ImageDemo
example.
Images can also be created at runtime from scratch. The static method
Image.create (int
width, int height)
creates a new dynamic image of the given size. In contrast to images loaded
from a JAR file, these images are mutable. Mutable images can be modified by calling
getGraphics()
. The
Graphics
object returned can be used for modifying the image with all the
methods provided by the
Graphics
class. Please note that images loaded from a JAR file cannot be
modified. However, it is possible to create a mutable image, and then draw any other image in the
mutable image.
By modifying the constructor of the previous example canvas as follows, the image drawn in the
paint()
method is created and filled at runtime instead of loading an image from the JAR file:
public ImageDemoCanvas() {
image = Image.createImage (10,10);
image.getGraphics().fillArc (0,0,10,10,0, 360);
}
The disadvantage of mutable images is that they cannot be used in high-level GUI elements since it is
possible to modify them at any time, possibly leading to inconsistent display of widgets. For that
reason, another static create method,
createImage(Image image)
, is provided that creates an
immutable image from another image.
Interaction
Because the
Canvas
class is a subclass of
Displayable
, it provides the same support for
commands as the high-level screen classes. Here, you will concentrate on the additional interaction
possibilities the
Canvas
class offers: direct key input and pointer support.
Please note that all input events and command notifications and the
paint()
method are called
serially. That means that the application manager will call none of the methods until the previous event
handling method has returned. So all these methods should return quickly, or the user will be unable to
interact with the application. For longer tasks, a separate thread can be started.
Key Input
For key input, the
Canvas
class provides three callback methods:
keyPressed()
,
keyReleased()
, and
keyRepeated()
. As the names suggest,
keyPressed()
is called when a
key is pressed,
keyRepeated()
is called when the user holds down the key for a longer period of
time, and
keyReleased()
is called when the user releases the key.
All three callback methods provide an integer parameter, denoting the Unicode character code assigned
to the corresponding key. If a key has no Unicode correspondence, the given integer is negative. MIDP
defines the following constant for the keys of a standard ITU-T keypad:
KEY_NUM0
,
KEY_NUM1
,
KEY_NUM2
,
KEY_NUM3
,
KEY_NUM4
,
KEY_NUM5
,
KEY_NUM6
,
KEY_NUM7
,
KEY_NUM8
,
Search WWH ::
Custom Search