Search code examples
imagecomponentscontainerslabelcodenameone

Components not displayed properly within containers in Codenameone


I have an issue with Codenameone not displaying components as a solid color image label within a container. It displays fine if the image is created from an actual photo.

This does not work (imageBlock is not displayed in the container):

Form form = new Form("Result", new BorderLayout());

Image solid = Image.createImage(350, 350, 0x0000ff);
Label imageBlock = new Label("", solid, "Container");
Label imageKey = new Label("Solid Image");
Container imageProfile = BoxLayout.encloseX(imageBlock, imageKey);
form.add(BorderLayout.NORTH, imageProfile);

This will work (imageBlock is displayed in the container):

Form form = new Form("Result", new BorderLayout());

Image photo = Image.createImage(Capture.capturePhoto(width, -1));
Label imageBlock = new Label("", photo.scaled(350, 350), "Container");
Label imageKey = new Label("Photo Image");
Container imageProfile = BoxLayout.encloseX(imageBlock, imageKey);
form.add(BorderLayout.NORTH, imageProfile);

Can anyone explain why the solid image label is not displayed in the container and what can I do to make it display?


Solution

  • The problem is that the create method for image uses an ARGB color, not an RGB color. You need to change that line to:

    Image solid = Image.createImage(350, 350, 0xff0000ff);
    

    Notice the ff in the start of the color for the alpha channel. Otherwise the color is transparent.

    Notice that it would be more efficient to style the label with a color instead of creating an image. You're effectively creating an image of 350x350x4 bytes which takes up memory. Doing something like this will be more efficient in terms of RAM and performance:

    // Space is needed since blank labels are hidden by default
    Label solid = new Label(" ");
    solid.setPreferredSize(350, 350);
    solid.getUnselectedStyle().setBgTransparency(0xff);
    solid.getUnselectedStyle().setBgColor(0xff);