Search code examples
codenameone

Why does button.getAllStyles().getBgImage() return null?


My test case:

Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hello World"));

Button button = new Button(" ");
button.getAllStyles().setBgImage(EncodedImage.createFromImage(Image.createImage(CN.convertToPixels(10), CN.convertToPixels(10), 0xffea5b0c), false));
button.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
hi.add(button);

hi.addShowListener(l -> {
    Image background = button.getAllStyles().getBgImage();
    Log.p("background is null? " + (background == null));
});

hi.show();

It logs:

background is null? true

Why does button.getAllStyles().getBgImage() return null? Is that my mistake or a Codename One bug?


Solution

  • Because the JavaDoc of getAllStyles() says:

    Returns a "meta style" that allows setting styles once to all the different Style objects, the getters for this style will be meaningless and will return 0 values

    The reason for this is obvious. Set all styles makes a lot of sense, you just loop over the style objects and set the new value.

    But what should get return? What if unselected and select differ?

    Use getUnselectedStyle() instead.