mgwt

How to add a custom image in MGWT ImageButton


I am new to mgwt , I just added ImageButton and simply trying to put my custom image in it

This is my button

   <b:ImageButton ui:field="imgButton_settings" > Settings   </b:ImageButton>

in my java class I am assigning this image resource to this button

      imgButton_settings.setIcon(Resources.INSTANCE.myIcon());

But the button image area is still black

I also tried this way

  ImageButton imageButton = new ImageButton("logo.png");

But no luck

Any Suggestions


Solution

  • You will need a few classes. First, is an image holder where you add your images:

    public class ImageHolder {
      private static final Appearance APPEARANCE = GWT.create(Appearance.class);
    
      public interface Appearance {
        public interface Images {
          ImageResource myIcon();
        }
        Images get();
      }
    
      public static Appearance.Images get() {
        return APPEARANCE.get();
      }
    }
    

    Then, you define 3 or 4 classes to get a different image based on a device pixel density:

    public class ImageHolderDefaultAppearance implements ImageHolder.Appearance {
      interface Resources extends ClientBundle, Images {
        Resources INSTANCE = GWT.create(Resources.class);
    
        @Override
        @Source("myIcon_mdpi.png")
        ImageResource myIcon();
      }
    
      @Override
      public Images get() {
        return Resources.INSTANCE;
      }
    }
    

    Similarly, you create a class ImageHolderDefaultHighAppearance with myIcon_hdpi.png, etc.

    In your gwt.xml file for this module you need to define deferred binding rules:

      <replace-with class="com.myClient.icons.ImageHolderDefaultAppearance">
        <when-type-is class="com.myClient.icons.ImageHolder.Appearance" />
      </replace-with>
      <replace-with class="com.myClient.icons.ImageHolderDefaultHighAppearance">
        <when-type-is class="com.myClient.icons.ImageHolder.Appearance" />
        <when-property-is name="mgwt.density" value="high" />
      </replace-with>
      <replace-with class="com.myClient.icons.ImageHolderDefaultXHighAppearance">
        <when-type-is class="com.myClient.icons.ImageHolder.Appearance" />
        <when-property-is name="mgwt.density" value="xhigh" />
      </replace-with>
    

    Now you can use these icons in your app by calling ImageHolder.get().myIcon()