Codename One runs on a wide range of hardware, from phones and tablets to desktops, foldables, and devices driven by a mouse or a stylus. This chapter covers the cross-platform APIs that expose that hardware: rich pointer detail (mouse buttons, pen pressure and tilt, the pointing device type), the mouse wheel, foldable device posture, and multi-display / desktop-window awareness.
These APIs are additive: on a device or platform that doesn’t report a given capability the value falls back to a sensible default, so a single code base keeps working everywhere.
Rich pointer events
The classic pointerPressed, pointerReleased and pointerDragged callbacks carry only the x/y
coordinates of the touch. Modern devices provide far more detail: which mouse button was used, the
kind of pointing device (finger, mouse, stylus or eraser), the pressure applied, the stylus tilt,
the contact area and the keyboard modifiers held at the time.
That detail is exposed through the immutable
PointerEvent
snapshot. There are two ways to read it.
From an ActionEvent
Any pointer listener receives an ActionEvent; call getPointerEvent() on it:
myComponent.addPointerPressedListener(e -> {
PointerEvent pe = e.getPointerEvent();
if (pe.isSecondaryButton()) {
showContextMenu(pe.getX(), pe.getY());
}
System.out.println("pressure=" + pe.getPressure() + " type=" + pe.getPointerType());
});By polling
When you’re inside a pointer callback you can also poll the current values directly from CN
(or Display), mirroring the existing CN.isShiftKeyDown() family:
int button = CN.getPointerButton(); // PointerEvent.BUTTON_PRIMARY, BUTTON_SECONDARY, ...
float pressure = CN.getPointerPressure(); // 0.0 - 1.0, defaults to 1.0
boolean pen = CN.isStylusPointer();
PointerEvent current = CN.getCurrentPointerEvent();BUTTON_PRIMARY, the pressure
is 1.0 and the type is TYPE_TOUCH (or TYPE_UNKNOWN on ports that don’t classify the device).Two and three button mice
PointerEvent.getButton() returns one of BUTTON_PRIMARY, BUTTON_SECONDARY, BUTTON_MIDDLE,
BUTTON_BACK or BUTTON_FORWARD. CN.getPressedButtonMask() returns a bitmask of every button
currently held (MASK_PRIMARY, MASK_SECONDARY, …), which is useful during a drag.
The real button is reported on every desktop port - macOS, Windows and Linux - and in the browser, so the right, middle and (where the mouse has them) back and forward buttons are all distinguished. On a plain touch screen there is only the primary button.
For the common case of a context menu, use the unified addContextMenuListener. It fires for a
secondary (right) mouse click, a stylus barrel button click and a long press, so the same code
handles desktop and touch:
label.addContextMenuListener(e -> {
e.consume(); // suppress the normal click/long-press handling
showMyContextMenu(e.getX(), e.getY());
});Mouse wheel and trackpad scrolling
By default the mouse wheel and trackpad scroll a scrollable container automatically. To react to
the wheel yourself - for example control plus wheel to zoom, or horizontal scrolling - add a
addMouseWheelListener. The listener receives a
WheelEvent;
consuming it prevents the default scroll.
A positive getDeltaY() reveals content above (the user scrolled down); a positive getDeltaX()
reveals content to the left. isPrecise() is true for high resolution devices such as trackpads.
On the desktop simulator, hold shift while turning the wheel to produce horizontal scrolling.
WheelEvent is a single universal scroll-gesture API: it’s fed by the mouse wheel and trackpad on
the desktop, by the wheel / external trackpad on Android, and by the trackpad, Magic Mouse and
mouse wheel on iOS and iPadOS (captured natively and routed through the same pipeline). Continuous
trackpad scrolling reports isPrecise() == true, while a notched wheel reports false. On the
Apple Watch the Digital Crown also feeds this same pipeline, so a list scrolls under the crown and a
mouse wheel listener receives the crown as a WheelEvent.
Trackpad gestures (magnify and rotate)
Beyond scrolling, the trackpad reports magnify (pinch) and rotate gestures. Override
pinch(float scale) to zoom and rotation(float radians) to rotate; both return true to mark the
gesture as handled. pinch is also driven by a two finger pinch on touch screens, so the same code
works on mobile and the desktop.
The trackpad gestures are wired on every desktop port: the macOS trackpad, the Windows touch screen
and gesture-capable touchpads (through the system WM_GESTURE messages), and the Linux touchpad
(through the GTK touchpad gesture events). scale is an incremental zoom factor (just above or below
1.0) and radians is the incremental rotation since the previous callback, so accumulate them to
track the total.
addMouseWheelListener that checks isControlDown() (shown above) if you target those devices.Stylus and pen support
When a stylus is used (Apple Pencil, S-Pen, Surface Pen) the pointer type is TYPE_STYLUS, or
TYPE_ERASER for the eraser end. The PointerEvent then also carries:
getPressure()- normalized pressure between0.0and1.0.getTiltX()/getTiltY()- tilt in degrees (altitude and azimuth on iOS).getContactSize()- normalized size of the contact area.
For drawing surfaces a dedicated addStylusListener fires on press, drag and release only when the
pointer is a stylus or eraser:
drawingArea.addStylusListener(e -> {
PointerEvent pe = e.getPointerEvent();
float width = 1f + pe.getPressure() * 9f; // pressure controls stroke width
if (pe.isEraser()) {
erase(pe.getX(), pe.getY());
} else {
drawPoint(pe.getX(), pe.getY(), width);
}
});Pen hover (the pen moving above the screen without touching, available on devices such as the S-Pen
and the M2 iPad with Apple Pencil) flows through the existing pointerHover callbacks; the snapshot
reports isHovering() as true.
Touch-enabled desktops are handled too: on a Windows or Linux PC with a touch screen the finger
reports TYPE_TOUCH, and a Windows pen reports TYPE_STYLUS, so the same drawing and gesture code
runs on a touch laptop as on a phone. Display.getInstance().isTouchScreenDevice() is true on those
machines.
Foldable devices and posture
Foldable and dual screen devices (Galaxy Fold, Galaxy Flip, Pixel Fold, Surface Duo) change shape
at runtime. Query the live posture through
DevicePosture:
DevicePosture p = CN.getDevicePosture();
// isTableTop() is true for book posture too, so check the hinge is
// horizontal before laying out top-and-bottom
if (p.isFoldable() && p.isTableTop()
&& p.getFoldOrientation() == DevicePosture.FOLD_ORIENTATION_HORIZONTAL) {
layoutForTableTop(p.getFoldBounds(null));
}getPosture()-POSTURE_FLAT,POSTURE_HALF_OPENED,POSTURE_CLOSEDorPOSTURE_UNKNOWN.getHingeAngle()- hinge angle in degrees (-1when unknown).getFoldOrientation()-FOLD_ORIENTATION_VERTICAL,FOLD_ORIENTATION_HORIZONTALorFOLD_ORIENTATION_NONE.getFoldBounds(Rectangle)- the region the hinge occludes, in display coordinates, or null when there is no separating fold. Treat it likeForm.getSafeArea(): keep interactive content out of it, or split a master and detail layout across the two halves.
React to fold changes with a posture listener:
class FoldAwareForm extends Form {
private ActionListener postureListener;
protected void initComponent() {
super.initComponent();
postureListener = e -> relayoutForPosture(CN.getDevicePosture());
CN.addPostureListener(postureListener);
}
protected void deinitialize() {
// CN registers on the singleton Display, so a screen that never
// unregisters stays reachable and keeps receiving posture changes
CN.removePostureListener(postureListener);
super.deinitialize();
}
}To exercise this in the desktop simulator, use the Simulate → Foldable menu: enable foldable mode, then pick a posture (flat, half-opened or closed), the fold orientation (vertical or horizontal) and the hinge angle. The running app receives the same posture changes and listener callbacks it would on a real foldable device.
A foldable skin goes further. The bundled iPhone Duo skin, or any skin built with the Skin Designer’s Fold tab, describes the hinge and the cover display, so the menu offers that device’s postures and a hinge-angle slider. A posture change animates the device folding in 3D. Closing it switches the app to the cover display, with that display’s size, density and safe area, exactly as the hardware does. The posture events arrive while the fold moves: half opened below 150 degrees, closed below 30, the thresholds Android’s Jetpack WindowManager uses. The fold button beside the rotate buttons in the simulator toolbar steps through the postures, and Animate fold in the menu turns the animation off when you only want the end state.
Rotating the device animates too, on every skin: the device lifts, turns a quarter and settles into the new orientation, still folded if it was.
Simulate → Record Device Tour… turns this into a demo video in one step. It records your app
while the device closes, opens, half folds, turns to landscape and back, then stops by itself and
names the saved MP4 (in ~/CodenameOneRecordings). A skin that doesn’t fold gets the turn alone.
The tour and any scripted recording render every video frame for its own moment of the animation, at 60 frames a second, so the video plays without stutter however long a frame takes to draw. While such a recording runs, the simulator window plays the motion in slow motion; that’s expected.
To record without any window on screen, start the simulator hidden: mvn cn1:agent
-Dcn1.agent.hidden=true (Gradle: ./gradlew cn1Agent -Pcn1.agent.hidden=true), or set
CN1_SIMULATOR_HIDDEN=1 in the environment. It renders exactly as it does with a window,
so screenshots, recordings and the MCP tools all work while you keep using the machine.
Every skin-framed recording is staged: a 16:9 backdrop with the device centered at one constant
size, so folding, moving to the cover display and rotating never rescale it. To script your own
clip, the simulator’s MCP tools take the fold too: sim_fold moves to a posture (posture is
flat, half or closed) or a hinge angle, over animateMs milliseconds, and
sim_record_start accepts a script, a list of steps such as
{"at": 2000, "posture": "half", "animateMs": 900} or {"at": 6000, "orientation": "landscape"}
that it plays from the start of the recording.
Toolbar, as new projects do by default.Foldable support on Android is opt-in so it never adds weight to apps that don’t use it. Enable it
with the android.foldableSupport=true build hint (the version can be overridden with
android.windowVersion). Note that the hinge angle isn’t available on Android, so
getHingeAngle() returns -1 there.
Desktop windowing and external displays
Some mobile devices run in a desktop windowing mode where the app shares the screen with other
windows: Samsung DeX, Android desktop windowing and iPad Stage Manager. CN.isDesktopMode()
reports this. It’s distinct from CN.isDesktop(), which reports a genuine desktop platform
(Windows, macOS or Linux).
CN.getDisplayCount() returns the number of attached displays and CN.isExternalDisplayConnected()
is a convenience for getDisplayCount() > 1. On the desktop port these reflect the real monitors
attached to the machine.
Apple TV remote
On Apple TV the Siri Remote is delivered through the standard key handling, so the same
keyPressed/keyReleased and game-key code you write for other platforms works on the TV. The
directional buttons map to the arrow / game keys, the click maps to enter (fire), the menu button
maps to the back key, and play/pause maps to the media play/pause key. No TV specific API is
required.
Haptics, system bars, brightness and battery
A few small device services have their own classes. On a platform that lacks the feature the call does nothing, or answers a value that means unknown. Every class has an isSupported() method for code that needs to know.
Haptic feedback
Haptics plays typed feedback: an impact (LIGHT, MEDIUM, HEAVY, SOFT, RIGID), a selection tick, or a notification (SUCCESS, WARNING, ERROR). iOS uses its feedback generators and Android uses the view’s haptic feedback constants. Where a port has no typed haptics, the call falls back to Display.vibrate with a matching duration:
Button save = new Button("Save");
save.addActionListener(e -> {
Haptics.impact(Haptics.MEDIUM);
// ... save the document ...
Haptics.notification(Haptics.SUCCESS);
});Using Haptics makes the Android build declare the VIBRATE permission. iOS needs no permission.
Status and navigation bars
SystemBars sets the status bar icon style, the status bar color, the Android navigation bar color, and whether the app draws behind the bars:
SystemBars.setStatusBarStyle(SystemBars.STYLE_LIGHT_CONTENT);
SystemBars.setStatusBarColor(0xff1a237e);
SystemBars.setNavigationBarColor(0xff1a237e, true);The colors and the navigation bar apply to Android. On iOS the title area of the form shows through the status bar, so only the icon style and visibility matter there. With setEdgeToEdge(true) the content draws behind both bars: keep it clear of them with the safe area insets.
Screen brightness
ScreenBrightness changes the brightness of the app window, from 0 to 1. It needs no permission. reset() hands control back to the system, and setKeepScreenOn keeps the screen awake:
// A boarding pass screen: full brightness, and the screen stays on
ScreenBrightness.set(1f);
ScreenBrightness.setKeepScreenOn(true);
// Later, when the user leaves the screen
ScreenBrightness.reset();
ScreenBrightness.setKeepScreenOn(false);Android applies the value to the window only. iOS has no window brightness, so it changes the screen brightness and reset() restores the value from before the first change.
Battery
Battery reports the charge level, the charging state and low power mode. A listener hears about changes on the EDT:
if (Battery.isLowPowerMode() || Battery.getLevel() < 15) {
Log.p("Skipping the background sync to save power");
}
Battery.addListener((level, state, lowPower) ->
Log.p("Battery " + level + "%, charging "
+ (state == Battery.STATE_CHARGING)));The level is -1 when the platform can’t tell. The simulator reports a full battery.
Dynamic colors
DynamicColors reads the system palette, which is Material You on Android 12 and newer. Pass a fallback for platforms with no palette:
int accent = DynamicColors.getColor(DynamicColors.ACCENT, 0x3f51b5);
Label title = new Label("Welcome");
title.getAllStyles().setFgColor(accent);Permissions
Permissions checks and requests runtime permissions in one place. It declares nothing itself. A permission reaches the Android manifest or the iOS Info.plist only because the build found a feature class that needs it, such as the camera or location API. A request for a permission that no feature declared answers DENIED, and the log says why:
int status = Permissions.check(Permissions.CAMERA);
if (status != Permissions.GRANTED) {
status = Permissions.request(Permissions.CAMERA,
"The camera scans the receipt");
}
if (status == Permissions.DENIED_PERMANENTLY) {
Log.p("Ask the user to enable the camera in Settings");
}request blocks until the user answers. On iOS it covers the camera, the microphone, location, contacts, photos, and notifications. Photos and notifications answer UNKNOWN unless the app also uses the gallery or push API that links their framework. Any other permission answers UNKNOWN on iOS; use the feature’s own API there, which asks on first use.
Saving to the gallery
MediaLibrary saves an image or a video file to the photo gallery. The callback runs on the EDT:
String photo = FileSystemStorage.getInstance().getAppHomePath() + "receipt.jpg";
MediaLibrary.saveImage(photo, "Receipts", new SuccessCallback<Boolean>() {
public void onSucess(Boolean saved) {
Log.p(saved ? "Saved to Photos" : "Could not save");
}
});Using MediaLibrary makes the build declare what it needs. On iOS that’s the NSPhotoLibraryAddUsageDescription string, which the ios.NSPhotoLibraryAddUsageDescription build hint can replace. On Android it’s WRITE_EXTERNAL_STORAGE for Android 9 and older only, because newer versions need no permission. Android puts the file in a folder named after the album. iOS saves to the camera roll and ignores the album. The simulator copies the file into a gallery folder in the app home.
App updates
AppUpdates finds out whether the store has a newer version of the app:
AppUpdates.check(new SuccessCallback<AppUpdates.UpdateInfo>() {
public void onSucess(AppUpdates.UpdateInfo info) {
if (info.isUpdateAvailable()) {
// false: a flexible update that downloads in the background
AppUpdates.startUpdate(false);
}
}
});On Android the build adds the Google Play in-app update library, and startUpdate shows the Play update flow. Pass true for an immediate update that blocks the app until it’s installed. On iOS the check asks the App Store lookup service for the version published under the bundle ID, and startUpdate opens the store page.
Background transfers
BackgroundTransfer downloads a URL to a file, or uploads a file as a form post, and reports progress and completion on the EDT:
String dest = FileSystemStorage.getInstance().getAppHomePath() + "episode.mp3";
BackgroundTransfer.download("https://example.com/episode.mp3", dest,
new BackgroundTransfer.Listener() {
public void onProgress(BackgroundTransfer.Transfer t, long done, long total) {
Log.p("Downloaded " + done + " of " + total);
}
public void onComplete(BackgroundTransfer.Transfer t, boolean success, int status) {
Log.p("Finished: " + success + ", HTTP " + status);
}
});A transfer keeps running while the app is in the background, for as long as the system keeps the app process alive. It doesn’t survive the end of the process: isProcessIndependent() answers false. Check for incomplete files when the app starts and restart those transfers.
Picture in picture
PictureInPicture shrinks the app into a floating window, so a video keeps playing while the user works in another app:
if (PictureInPicture.isSupported()) {
PictureInPicture.addListener(new SuccessCallback<Boolean>() {
public void onSucess(Boolean active) {
Log.p("Hide the player controls: " + active);
}
});
PictureInPicture.enter(16, 9);
}It works on Android 8 and newer. The whole app window becomes the floating window, so hide everything but the video while the listener reports true. Using the class makes the Android build mark the main activity as supporting picture in picture. On iOS and in the simulator isSupported() answers false.
Haptic patterns
Haptics.pattern plays a sequence of buzzes. The array alternates "off" and "on" times in milliseconds, starting with a pause:
// Wait 0 ms, buzz 40 ms, pause 80 ms, buzz 120 ms.
Haptics.pattern(new long[] {0, 40, 80, 120});Android plays the pattern with the vibrator. iOS has no vibration pattern call, so each "on" time becomes one impact: short times play a light impact and long times a heavy one. Ports without haptics play the first "on" time with Display.vibrate.
Apple Pay and Google Pay
PlatformPay shows the wallet payment sheet and returns an encrypted payment token. It never charges the card. Send the token to your server, which passes it to your payment service provider, such as Stripe or Adyen:
PlatformPay.Request req = new PlatformPay.Request("Coffee", "4.50", "USD", "US");
req.setMerchantId("merchant.com.example.shop");
req.setGateway("stripe", "pk_test_123");
if (PlatformPay.isSupported()) {
PlatformPay.requestPayment(req, new SuccessCallback<PlatformPay.Result>() {
public void onSucess(PlatformPay.Result r) {
if (r.getStatus() == PlatformPay.Result.SUCCESS) {
Log.p("Send to the server: " + r.getToken());
// When the server has charged the token, close the
// sheet with the outcome. Here it is assumed to work.
r.complete(true);
} else if (r.getStatus() == PlatformPay.Result.FAILED) {
Log.p("Payment failed: " + r.getError());
}
}
});
}On iOS the Apple Pay sheet waits, showing progress, until you call complete with the outcome of the charge. Call it once your server answers. Without a call, the sheet shows a failure after 30 seconds. Google Pay closes its sheet when it returns the token, so complete does nothing there.
On iOS the token is the base64 form of the Apple Pay paymentData. On Android it’s the Google Pay token for the gateway you set with setGateway. Use Purchase for digital goods, because the stores don’t allow wallet payments for those.
Using the class makes the iOS build link PassKit. Apple Pay also needs the merchant id in the app’s entitlements. List your merchant ids in the ios.applePayMerchantIds build hint, separated by commas, and the build writes the com.apple.developer.in-app-payments entitlement. The Android build adds the Google Play Services wallet library and enables the Google Pay API in the manifest.
Casting media
Cast sends media to a TV or a speaker. Cast.getPlatform() is AirPlay on iOS. GoogleCast.getInstance() is Google Cast on Android:
Cast cast = GoogleCast.getInstance();
if (!cast.isSupported()) {
cast = Cast.getPlatform();
}
final Cast session = cast;
session.addStateListener(new SuccessCallback<Integer>() {
public void onSucess(Integer state) {
if (state.intValue() == Cast.STATE_CONNECTED) {
session.load("https://example.com/movie.mp4", "video/mp4",
"Movie", "Trailer", null, 0);
}
}
});
session.showRoutePicker();showRoutePicker opens the system device picker and answers whether it could. iOS has no public call that opens the AirPlay picker, so the port taps the button inside the system route picker view. This is best effort: if a future iOS changes that view, the call answers false. With Google Cast the receiver plays the URL you pass to load, and play, pause, seek and stop control it. AirPlay moves the app’s own audio and video to the chosen device, so load answers false there: keep playing the media in the app. Where a route isn’t available, isSupported() answers false, so the snippet falls back from Google Cast to the platform route.
On Android, referencing GoogleCast adds the Google Cast framework to the build and raises the minimum SDK to 23. Apps that use only Cast.getPlatform() don’t get the dependency. The device picker is a plain list of the Cast devices on the network. State listeners run on the EDT.
The receiver is Google’s Default Media Receiver, which plays a media URL with no setup. To use a custom or styled receiver, register it in the Google Cast SDK Developer Console and set its application ID with the android.googleCastReceiverAppId build hint.