ButtonField image

Hy guys

That's the problem

BitmapField bfSeat = new BitmapField (Bitmap.getBitmapResource ("seat_service.png"), BitmapField.FOCUSABLE);
bfSeat.setChangeListener (new FieldChangeListener() {}
' Public Sub fieldChanged (field field, int context) {}

When I click on the image, I can see the menu see the keyboard, the full menu! but I wish to draw the button!

i' is added ... Bot BitmapField.FOCUSABLE there does not work...

Why?

Find the attached file.

Tags: BlackBerry Developers

Similar Questions

  • put image in buttonField?

    Hello, I would like to know how can I put an image in a buttonField, first is it possible?

    It's my code. It can help you

    package maz.fields.button;
    
    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.Graphics;
    
    public class ImageButtonField extends Field{
    
        Bitmap _unfocus,_focus,_unfocus_selected,_focus_selected;
        boolean isSelect = false;
    
        public ImageButtonField(Bitmap unfocus, Bitmap focus,long style) {
            // TODO Auto-generated constructor stub
            super(style);
            _unfocus = unfocus;
            _focus = focus;
        }
    
        public ImageButtonField(Bitmap unfocus, Bitmap focus, Bitmap selected ,long style) {
            // TODO Auto-generated constructor stub
            super(style);
            _unfocus = unfocus;
            _focus = focus;
            _unfocus_selected = selected;
        }
    
        public ImageButtonField(Bitmap unfocus, Bitmap focus, Bitmap unfocus_selected, Bitmap focus_selected ,long style) {
            // TODO Auto-generated constructor stub
            super(style);
            _unfocus = unfocus;
            _focus = focus;
            _unfocus_selected = unfocus_selected;
            _focus_selected = focus_selected;
        }
    
        public void set_unfocus(Bitmap _unfocus) {
            this._unfocus = _unfocus;
        }
    
        public void set_focus(Bitmap _focus) {
            this._focus = _focus;
        }
    
        public int retriveHeight(){
            return _unfocus.getHeight();
        }
    
        public int retriveWidth(){
            return _unfocus.getWidth();
        }
    
        public void setSelect(boolean _isSelect){
            isSelect = _isSelect;
            invalidate();
        }
    
        public boolean getSelect(){
            return isSelect;
        }
    
        protected void paint(Graphics graphics) {
            // TODO Auto-generated method stub
                if(!isFocus()){
                    if(isSelect){
                        graphics.drawBitmap(0, 0, _unfocus_selected.getWidth(), _unfocus_selected.getHeight(), _unfocus_selected, 0, 0);
                    }else{
                        graphics.drawBitmap(0, 0, _unfocus.getWidth(), _unfocus.getHeight(), _unfocus, 0, 0);
                    }
                }else {
                    if(_focus_selected!=null){
                        if(isSelect){
                            graphics.drawBitmap(0, 0, _focus_selected.getWidth(), _focus_selected.getHeight(), _focus_selected, 0, 0);
                        }else{
                            graphics.drawBitmap(0, 0, _focus.getWidth(), _focus.getHeight(), _focus, 0, 0);
                        }
                    }else{
                        graphics.drawBitmap(0, 0, _focus.getWidth(), _focus.getHeight(), _focus, 0, 0);
                    }
                }
        }
    
        public boolean isFocusable() {
            return true;
        }
    
        protected void drawFocus(Graphics graphics, boolean on) {
        }
    
        protected void onFocus(int direction) {
            super.onFocus(direction);
            invalidate();
        }
    
        protected void onUnfocus() {
            super.onUnfocus();
            invalidate();
        }
    
        protected void layout(int width, int height) {
            setExtent(_focus.getWidth(), _focus.getHeight());
        }
    }
    

    MAZ

  • Problem with a Bitmap image in a ButtonField (get a 104 NullPointerException error)

    Hi, I'm a beginner in programming BlackBerry Apps, well...

    I tried to create a simple ButtonField customized with a bitmap inside, but I constantly get an error 104 eception: NullPointerException, here is my code to field custom buttond.

    import net.rim.device.api.ui.component.ButtonField;import net.rim.device.api.ui.Graphics;import net.rim.device.api.system.Bitmap;
    
    public class CustomButtonField extends ButtonField{  
    
      private Bitmap imagen;
    
      CustomButtonField(Bitmap imagen, long style){
    
          super(style);     this.imagen = imagen;                     }
    
      public int getPreferredWidth(){
    
                    return 60;        }
    
      public int getPreferredHeight(){
    
          return 60;        }
    
     protected void paint(Graphics graphics) {
    
          graphics.drawBitmap(0, 0, imagen.getWidth(), imagen.getHeight(), imagen, 0, 0);   }
    
       protected void layout(int width, int height) {
    
          setExtent(getPreferredWidth(), getPreferredHeight());
    
        }  }
    
    import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.system.Bitmap;
    
    public class PruebaScreen extends MainScreen{    
    
      private CustomButtonField boton;
    
      PruebaScreen(){
    
          Bitmap imagen = Bitmap.getBitmapResource("res/img/icon.png");     boton = new CustomButtonField(imagen, 0);     add(boton);
    
      }}
    

    I suspect that my problem is due to the method of painting or the page layout, I don't know... I hope someone can help me, thank you very much in advance.

    Check if your getBitmapResource returns any non-null Bitmap image.  Specify the path correctly may take a few tries ("' / res/img/icon.png '," img/icon.png", etc.")

  • ButtonField personalized with images

    Hi all

    I am trying to create a custom ButtonField, I'm unable to remove the background gray color. Could someone tell me what's wrong with this code?

    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.ui.Color;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.Font;
    import net.rim.device.api.ui.FontFamily;
    import net.rim.device.api.ui.Graphics;
    import net.rim.device.api.ui.component.ButtonField;
    
    public class BigButtonField extends ButtonField{
    
        private int backgroundColour = Color.BLACK;
        private Bitmap button;
        private Bitmap on = Bitmap.getBitmapResource("onbutton.png");
        private Bitmap off = Bitmap.getBitmapResource("offbutton.png");
        private int fieldWidth = Graphics.getScreenWidth();
        private int fieldHeight = 31;
        private int buffer = (Graphics.getScreenWidth() - 105) / 2;
        private String text;
        private Font fieldFont;
    
        public BigButtonField(String _text) {
            super(Field.FOCUSABLE);
            this.text = _text;
            button = off;
            fieldFont = FieldFont();
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        protected boolean navigationClick(int status, int time) {
            fieldChangeNotify(1);
            return true;
        }
    
        protected void onFocus(int direction){
            button = on;
            invalidate();
        }
    
        protected void onUnfocus(){
            button = off;
            invalidate();
        }
    
        public int getPreferredWidth() {
            return fieldWidth;
        }
    
        public int getPreferredHeight() {
            return fieldHeight;
        }
    
        protected void layout(int arg0, int arg1) {
            setExtent(getPreferredWidth(), getPreferredHeight());
        }
    
        public static Font FieldFont() {
            try {
                FontFamily theFam = FontFamily.forName("SYSTEM");
                return theFam.getFont(net.rim.device.api.ui.Font.BOLD, 14);
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            return null;
        }
    
        protected void drawFocus(Graphics graphics, boolean on){
            //
        }
    
        protected void fieldChangeNotify(int context){
            try {
                this.getChangeListener().fieldChanged(this, context);
            } catch (Exception exception) {
            }
        }
    
        protected void paint(Graphics graphics) {
            graphics.drawRect(0, 0, fieldWidth, fieldHeight);
            graphics.fillRect(10, 0, fieldWidth-200, fieldHeight);
            graphics.drawBitmap(0, 0, fieldWidth, fieldHeight, button, 0, 0);
            graphics.setColor(Color.BLACK);
            graphics.setFont(fieldFont);
            graphics.drawText(text, ((fieldWidth - fieldFont.getAdvance(text))/ 2) - 70, (fieldHeight - fieldFont.getHeight()) / 2);
        }
    }
    

    Please provide your suggestion. If you have any other sample for buttonField customized by using bitmap then please share here.

    Buzz.

    Hi all

    I found the solution myself.

    1. I spread "Field" in my code, which removed the gray area of the background.

    2. I added a FieldChanglistner to the customed button whenever I use it.

    Yet once again thanks to you.

    Buzz.

  • Add ButtonField on BitmapFiled

    Hi all

    I tried to use this code to add BitmapButtonField on BitmapField but I couldn't use it.

    Ant one can help me?

    package mypackage;
    
    import com.operations.images.ImageManipulator;
    
    import net.rim.device.api.system.Application;
    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.system.Display;
    import net.rim.device.api.system.JPEGEncodedImage;
    import net.rim.device.api.ui.TouchEvent;
    import net.rim.device.api.ui.TouchGesture;
    import net.rim.device.api.ui.UiApplication;
    import net.rim.device.api.ui.component.BitmapField;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.Dialog;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.component.SeparatorField;
    import net.rim.device.api.ui.container.MainScreen;
    import net.rim.device.api.ui.container.VerticalFieldManager;
    
    /**
     * A class extending the MainScreen class, which provides default standard
     * behavior for BlackBerry GUI applications.
     */
    public final class MyScreen extends MainScreen {
    
        private static int rotatedAngle = 360;
    
        // byte[] rrr = resizeImage(Bitmap.getBitmapResource("gear.png"),
        // Display.getWidth(), Display.getHeight() / 2);
        // Bitmap originalBmp = Bitmap.createBitmapFromBytes(rrr, 0, rrr.length, 1);
        Bitmap originalBmp = Bitmap.getBitmapResource("[email protected]");
        BitmapField rotatedBitmap = new BitmapField(originalBmp);
    
        private BitmapButtonField buttonField1 = new BitmapButtonField(
                Bitmap.getBitmapResource("images_1.png"));
        private BitmapButtonField buttonField2 = new BitmapButtonField(
                Bitmap.getBitmapResource("images_2.png"));
    
        VerticalFieldManager bmpManager = new VerticalFieldManager(USE_ALL_WIDTH
                | NO_HORIZONTAL_SCROLL | NO_VERTICAL_SCROLL) {
    
            public int getPreferredHeight() {
                return rotatedBitmap.getHeight();
            };
    
            public int getPreferredWidth() {
                return rotatedBitmap.getWidth();
            };
    
            protected void sublayout(int maxWidth, int maxHeight) {
    
                layoutChild(rotatedBitmap, originalBmp.getWidth(),
                        originalBmp.getHeight());
                layoutChild(buttonField1, buttonField1.getPreferredWidth(),
                        buttonField1.getPreferredHeight());
                layoutChild(buttonField2, buttonField2.getPreferredWidth(),
                        buttonField2.getPreferredHeight());
    
                setPositionChild(rotatedBitmap, 0, 0);
                setPositionChild(buttonField1, 0, 50);
                setPositionChild(buttonField2, 50, 50);
    
                super.sublayout(getPreferredWidth(), getPreferredHeight());
                setExtent(getPreferredWidth(), getPreferredHeight());
    
            };
        };
    
        VerticalFieldManager manager = new VerticalFieldManager(USE_ALL_WIDTH
                | NO_HORIZONTAL_SCROLL | NO_VERTICAL_SCROLL) {
    
            public int getPreferredHeight() {
                return Display.getHeight() - bmpManager.getPreferredHeight();
            };
    
            public int getPreferredWidth() {
                return Display.getWidth();
            };
        };
    
        /**
         * Creates a new MyScreen object
         */
        public MyScreen() {
            super(USE_ALL_WIDTH | USE_ALL_HEIGHT);
            // Set the displayed title of the screen
            setTitle("Test Animation");
    
            bmpManager.add(rotatedBitmap);
            bmpManager.add(buttonField1);
            bmpManager.add(buttonField2);
    
            manager.add(new SeparatorField());
            manager.add(new SeparatorField());
            manager.add(new LabelField(" label 1 "));
            manager.add(new LabelField(" label 2 "));
            manager.add(new LabelField(" label 3 "));
    
            add(bmpManager);
    
            add(manager);
    
        }
    
        protected boolean touchEvent(TouchEvent message) {
            switch (message.getEvent()) {
            case TouchEvent.CLICK:
                // invokeDialog("-->CLICK");
                return true;
            case TouchEvent.DOWN:
                // invokeDialog("-->DOWN");
                return true;
    
            case TouchEvent.GESTURE:
                TouchGesture gesture = message.getGesture();
                int gestureCode = gesture.getEvent();
    
                if (gesture.getSwipeDirection() == TouchGesture.SWIPE_NORTH) {
                    invokeDialog("swip north : " + gesture.getSwipeAngle() + " , "
                            + gesture.getSwipeMagnitude());
                } else if (gesture.getSwipeDirection() == TouchGesture.SWIPE_SOUTH) {
                    invokeDialog("swip south : " + gesture.getSwipeAngle() + " , "
                            + gesture.getSwipeMagnitude());
                } else if (gesture.getSwipeDirection() == TouchGesture.SWIPE_EAST) {
                    if ((message.getX(1) >= bmpManager.getContentRect().x && message
                            .getX(1) <= bmpManager.getContentRect().width)
                            && (message.getY(1) >= bmpManager.getContentRect().y && message
                                    .getY(1) <= bmpManager.getContentRect().height)) {
    
                        // invokeDialog("swip east : " + gesture.getSwipeAngle()
                        // + " , " + gesture.getSwipeMagnitude());
                        rotate(true);
    
                    }
                } else if (gesture.getSwipeDirection() == TouchGesture.SWIPE_WEST) {
                    if ((message.getX(1) >= bmpManager.getContentRect().x && message
                            .getX(1) <= bmpManager.getContentRect().width)
                            && (message.getY(1) >= bmpManager.getContentRect().y && message
                                    .getY(1) <= bmpManager.getContentRect().height)) {
    
                        // invokeDialog("x = " + bmpManager.getContentRect().x +
                        // " , "
                        // + bmpManager.getContentRect().width + " \ny = "
                        // + bmpManager.getContentRect().y + " , "
                        // + bmpManager.getContentRect().height + "\n mx = "
                        // + message.getX(1) + " , " + message.getY(1));
                        // invokeDialog("swip west : " + gesture.getSwipeAngle()
                        // + " , " + gesture.getSwipeMagnitude());
                        rotate(false);
    
                    }
                }
    
                return true;
    
            case TouchEvent.MOVE:
                // int moveSize = message.getMovePointsSize();
                // int[] x_points;
                // int[] y_points;
                // int[] time_points;
                // int size = message.getMovePointsSize();
                // x_points = new int[size];
                // y_points = new int[size];
                // time_points = new int[size];
                // message.getMovePoints(1, x_points, y_points, time_points);
                //
                // if (x_points.length >= 50) {
                // invokeDialog("-->move : " + size);
                // }else if(x_points.length == 2){
                // invokeDialog("-->move : ssss = " + 2);
                // }
                return true;
            }
            System.out.println("PRINT ME SOMETHING IN ANY CASE");
            return false;
        }
    
        private void rotate(final boolean east) {
    
            synchronized (Application.getEventLock()) {
                UiApplication.getUiApplication().invokeLater(new Runnable() {
    
                    public void run() {
                        // wipe east
                        if (east) {
                            // if (rotatedAngle >= 0) {
                            for (int i = 0; i < 45; i += 1) {
                                try {
                                    rotatedAngle -= i;
                                    rotatedBitmap.setBitmap(ImageManipulator
                                            .rotate(originalBmp, rotatedAngle));
                                    bmpManager.invalidate();
                                    // bmpManager.deleteAll();
                                    // bmpManager.add(new
                                    // BitmapField(rotatedBitmap));
    
                                    // Thread.sleep(100);
                                } catch (Exception e) {
                                }
                            }
                            // }
                        } else {
                            // swipe weast
                            // if (rotatedAngle <= 360) {
                            for (int i = 0; i < 45; i += 1) {
                                try {
                                    rotatedAngle += i;
                                    rotatedBitmap.setBitmap(ImageManipulator
                                            .rotate(originalBmp, rotatedAngle));
                                    bmpManager.invalidate();
                                    // bmpManager.deleteAll();
                                    // bmpManager.add(new
                                    // BitmapField(rotatedBitmap));
    
                                    // Thread.sleep(100);
                                } catch (Exception e) {
                                }
                            }
                            // }
    
                        }
                    }
                });
    
            }
        }
    
        public static void invokeDialog(final String msg) {
            UiApplication.getUiApplication().invokeLater(new Runnable() {
    
                public void run() {
                    Dialog.inform(msg);
                }
            });
        }
    
        public static byte[] resizeImage(Bitmap srcBitmap, int width, int height) {
            // int width = 0;
            // int height = 0;
            // Bitmap srcBitmap = Bitmap.createBitmapFromBytes(image, 0,
            // image.length,
            // 1);
            // if (srcBitmap.getWidth() > srcBitmap.getHeight()) {
            // width = widthT;
            // height = (widthT * srcBitmap.getHeight()) / srcBitmap.getWidth();
            // } else if (srcBitmap.getWidth() < srcBitmap.getHeight()) {
            // height = heightT;
            // width = (height * srcBitmap.getWidth()) / srcBitmap.getHeight();
            // } else {
            // width = widthT;
            // height = heightT;
            // }
            Bitmap destBitmap = new Bitmap(width, height);
            srcBitmap.scaleInto(destBitmap, Bitmap.FILTER_BILINEAR);
            JPEGEncodedImage encoded = JPEGEncodedImage.encode(destBitmap, 100);
            return encoded.getData();
        }
    }
    

    Thank you

    I tried to improve my code and I found the solution

    /**
     * @author : Ahmed Shoeib
     * @description : add BitmapButtonField over BitmapField
     */
    public final class MyScreen extends MainScreen {
    
        Bitmap originalBmp = Bitmap.getBitmapResource("[email protected]");
        BitmapField rotatedBitmap = new BitmapField(originalBmp);
    
        BitmapButtonField buttonField1 = new BitmapButtonField(
                Bitmap.getBitmapResource("images_1.png"));
        BitmapButtonField buttonField2 = new BitmapButtonField(
                Bitmap.getBitmapResource("images_2.png"));
    
        Manager mainManager = new Manager(USE_ALL_WIDTH | NO_HORIZONTAL_SCROLL
                | NO_VERTICAL_SCROLL) {
    
            public int getPreferredHeight() {
                return rotatedBitmap.getHeight();
            };
    
            public int getPreferredWidth() {
                return rotatedBitmap.getWidth();
            };
    
            protected void sublayout(int width, int height) {
    
                setPositionChild(rotatedBitmap, 0, 0);
                layoutChild(rotatedBitmap, rotatedBitmap.getPreferredWidth(),
                        rotatedBitmap.getPreferredHeight());
    
                setPositionChild(buttonField1, getPreferredWidth() / 2, 0);
                layoutChild(buttonField1, buttonField1.getPreferredWidth(),
                        buttonField1.getPreferredHeight());
    
                setPositionChild(buttonField2, getPreferredWidth() / 2,
                        getPreferredHeight() / 2);
                layoutChild(buttonField2, buttonField2.getPreferredWidth(),
                        buttonField2.getPreferredHeight());
    
                setExtent(getPreferredWidth(), getPreferredHeight());
            }
        };
    
        VerticalFieldManager bottomManager = new VerticalFieldManager(USE_ALL_WIDTH
                | NO_HORIZONTAL_SCROLL | NO_VERTICAL_SCROLL) {
    
            public int getPreferredHeight() {
                return Display.getHeight() - mainManager.getPreferredHeight();
            };
    
            public int getPreferredWidth() {
                return Display.getWidth();
            };
        };
    
        /**
         * Creates a new MyScreen object
         */
        public MyScreen() {
            super(USE_ALL_WIDTH | USE_ALL_HEIGHT);
            // Set the displayed title of the screen
            setTitle("Test Animation");
    
            mainManager.add(rotatedBitmap);
            mainManager.add(buttonField1);
            mainManager.add(buttonField2);
    
            bottomManager.add(new LabelField("fffffffffff"));
            bottomManager.add(new LabelField("fffffffffff"));
            bottomManager.add(new LabelField("fffffffffff"));
    
            add(mainManager);
            add(bottomManager);
    
        }
    
    }
    

    Thank you

  • How to make Custom Bitmap ButtonField background transparent and not black?

    I have a buttonfield bitmaps customized using a png with transparent rounded corners. It appears as a black rectangle with the image on it. How can I make transparent blackground? I think that my problem lies in this code and I tried to use "alpha" with no results:

    Protected Sub paintBackground (Graphics Graphics) {}

    try {}
    graph.setGlobalAlpha (0);
    graph.setBackgroundColor (Color.BLACK);
    Graph.Clear ();
    }
    Finally {}
    }

    I'm sure it's a simple answer, but thanks anyway for the help!

    So I tried to do the same thing to paint override, and now the buttons are not displayed at all the haha. In any case, another programmer has helped me too and came up with the following code, it works and the problem is resolved. Thanks for your help guys, I'll put 'likes' for you. If anyone needs the code here, this is:

    SerializableAttribute public class BitmapButtonField extends {field}
    _onPicture private bitmap;
    _offPicture private bitmap;
    private int id;

    public BitmapButtonField (Bitmap onImage, Bitmap offImage) {}
    Super(Field.FOCUSABLE |) Field.FIELD_HCENTER);
    _offPicture = offImage;
    _onPicture = onImage;
    }

    {public setButtonImage Sub (onImage, offImage Bitmap Bitmap)
    _offPicture = offImage;
    _onPicture = onImage;
    }

    {} public void setButtonId (int id)
    This.ID = id;
    }

    public int getButtonId() {}
    return this.id;
    }

    public int getPreferredHeight() {}
    Return _onPicture.getHeight ();
    }

    public int getPreferredWidth() {}
    Return _onPicture.getWidth ();
    }

    protected void drawFocus (Graphics g, boolean on) {}
    }

    Protected Sub layout (int width, int height) {}
    setExtent (Math.min (width, getPreferredWidth()),
    Math.min (height, getPreferredHeight()));
    }

    Protected Sub paint (Graphics Graphics) {}
    graph.drawBitmap (0, 0, getWidth(), getHeight(), isFocus()? _onPicture: _offPicture, 0, 0);
    }

    protected boolean navigationClick (int status, int time) {}
    fieldChangeNotify (0);
    Returns true;
    }

    {} public boolean keyChar (key char, int status, int time)
    If (key == Characters.ENTER) {}
    fieldChangeNotify (0);
    Returns true;
    }
    Returns false;
    }
    }

  • ButtonField with background

    Hi guys,.

    I have a ButtonField customized with a background image. Here is an excerpt of my layout code

    myWidth = (int) ((double) bgOff.getWidth ());
    myHeight = (int) ((double) bgOff.getHeight ());

    setExtent (myWidth, myHeight);

    This will outline the dimensions of the ButtonField to adapt to that of the background image.

    In my painting method, I use drawBitmap to extract the background image. Here is my code.

    graphics.drawBitmap (0, 0, bgOn.getWidth (), bgOn.getHeight (), bgOn, 0, 0);

    However, this translates the background image that emerges only. I would like to have my main bitmap image on top of the background image. Centralize, if possible. Is it possible to do it this way?

    You probably forgot to put the super.paint (graphics) in your code somewhere - paint does not call as if by magic of painting of the superclass (which is what attracts this button according to focus etc..)

    A cleaner solution would be

    protected void paintBackground(Graphics graphics) {
        graphics.drawBitmap(0,0,getWidth(),getHeight(),bgOn,0,0);
    }
    

    This call is little documented, but it works.  Just look for paintBackground under the screen and you will suddenly discover that it replace another call paintBackground undocumented in the field.

    For what is centralized - you will need a few things for it.  You may be able to do this with Graphics.pushContext ().  Another approach would be like this:

    public class CenteringManager extends Manager {
      private Bitmap _bgOn;
      private int _bgWidth;
      private int _bgHeight;
      private int _width;
      private int _height;
    
      public CenteringManager(Bitmap bg) {
        _bgOn = bg;
        if (_bgOn != null) {
          _bgWidth = _bgOn.getWidth();
          _bgHeight = bgOn.getHeight();
        }
      }
    
      public int getPreferredWidth() {
        return _bgWidth;
      }
    
      public int getPreferredHeight() {
        return _bgHeight;
      }
    
      protected void sublayout(int w, int h) {
        _width = w;
        _height = h;
        if (_bgOn != null) {
          _width = Math.min(_width, _bgWidth);
          _height = Math.min(_height, _bgHeight);
        }
        if (getFieldCount() > 1) {
          throw new IllegalStateException("Cannot center more than one field.");
        }
        if (getFieldCount() > 0) { // there is one!
          Field onlyChild = getField(0);
          int childX;
          int childY;
          layoutChild(onlyChild, _width, _height);
          childX = (_width - onlyChild.getWidth()) / 2;
          if (childX < 0) {
            childX = 0;
          }
          childY = (_height - onlyChild.getHeight()) / 2;
          if (childY < 0) {
            childY = 0;
          }
          setPositionChild(onlyChild, childX, childY);
        }
        setExtent(_width, _height);
      }
    
      protected void paintBackground(Graphics g) {
        if (_bgOn != null) {
          g.drawBitmap(0,0,_width,_height,_bgOn,0,0);
        } else {
          g.clear();
        }
      }
    }
    

    You add your ButtonField to a CenteringManager instance (created in the background image you want) then you add to the screen of the Manager / which you would add normally as ButtonField.

  • How to display the Image on the screen.

    I was New in aid of BB.Plz.

    I am facing the problem is, I go get web Image.

    But how do I show on the extraction of Screen.For that I write code like this,

    If there's a problem with this code, then how may - I, please Hepl me out.

    import java. IO;
    Javax.microedition.io import. *;
    Net.rim.device.api.ui.component import. *;
    Net.rim.device.api.ui.container import. *;
    Net.rim.device.api.ui import. *;
    Javax.microedition.lcdui import. *;
    Javax.microedition.midlet import. *;

    showImage class extends FieldChangeListener implements screen
    {
    ButtonField down;
    Image img;
    ImageItem IM/it;
    public showImage()
    {
    LabelField title = new LabelField ("Image Download Example", LabelField.ELLIPSIS |) LabelField.USE_ALL_WIDTH);
    setTitle (title);
    down = new ButtonField ("Download");
    down.setChangeListener (this);
    Add (Down);
           
    }
        
    Public Image startImage()
    {
    String url = "http://media1.santabanta.com/full4/bikes/triumph/triumph-20d.jpg";
    HttpConnection hc = null;
    DataInputStream tell = null;
    Try
    {
    HC = (HttpConnection) Connector.Open (URL);
    hc.setRequestMethod (HttpConnection.GET);
    int st = hc.getResponseCode ();
    if(St==HttpConnection.HTTP_OK)
    {
    int len = (int) hc.getLength ();
    System.out.println ("==> Code" + hc.getResponseCode ());
    System.out.println ("Message ==>" + hc.getResponseMessage ());
    BTS Byte = new byte [len];
    tell = new DataInputStream (hc.openInputStream ());
    dis.readFully (bts);
    IMG = image.createImage (BTS, 0, Len);
    tell. Close();
    HC. Close();

    }

    } catch (Exception e) {}
    return img;
    }
    ' Public Sub fieldChanged (field f, int c)
    {
    if(f==Down)
    {
    Image image = startImage ();
    Add (image);
    }
    }
    }

    Take a look at these classes:

    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.system.EncodedImage;
    import net.rim.device.api.ui.image.Image;
    import net.rim.device.api.ui.component.BitmapField;
    

    This code should do you need:

            EncodedImage image = EncodedImage.createEncodedImage(data, offset, length);
            BitmapField bitmapField = new BitmapField();
            bitmapField.setImage(image);
            add(bitmapField);
    
  • Get all the images of devices, but how do I know in what images is seclected

    Hello

    in my application I want to show all the images in the first screen, after selecting any image in all we will see in the next screen (full screen) actually I get all images but problem how do I know what image is clicked

    I used this code...

    package mypackage;

    import java.io.IOException;
    import java.io.InputStream;
    to import java.util.Enumeration;
    import java.util.Vector;

    Import javax.microedition.io.Connector;
    Import javax.microedition.io.file.FileConnection;

    Import net.rim.device.api.math.Fixed32;
    Import net.rim.device.api.system.Bitmap;
    Import net.rim.device.api.system.EncodedImage;
    Import net.rim.device.api.ui.Field;
    Import net.rim.device.api.ui.Manager;
    Import net.rim.device.api.ui.component.BitmapField;
    Import net.rim.device.api.ui.component.ButtonField;
    Import net.rim.device.api.ui.container.FlowFieldManager;
    Import net.rim.device.api.ui.container.MainScreen;
    Import net.rim.device.api.util.Comparator;
    Import net.rim.device.api.util.SimpleSortingVector;

    /**
    * A class that extends the class screen, which offers default standard
    * behavior for BlackBerry GUI applications.
    */
    / public final class screen extends MyScreen
    {

    private static final String DEVICE_DIR_PATH = System
    .getProperty ("fileconn.dir.photos");
    private static final String SD_IMAGE_DIR_PATH = System
    .getProperty ("fileconn.dir.memorycard.photos");
    private static final String OS6_CAMERA_PATH = "file:///store/home/user/camera/";
    private static final String OS6_SD_CARD_PATH = "file:///SDCard/BlackBerry/camera/";

    public static final int DEVICE_AND_SD = 0;
    public static final int DEVICE_MEM = 1;
    public static final int SD_CARD = 2;
    public static final int OS6_CAMERA = 3;
    public static final int OS6_SD_CAMERA = 4;
    public static final int DEVICE_ALL = 5;
    private static String [] _allImagePaths = null;
    private EncodedImage [encodedbitmap];
    Private bitmap image in Bitmap [];
    private BitmapField [imagebitmapField];

    int dataSize;
    private ButtonField [] bitmapf;

    /**
    * Creates a new object of MyScreen
    */
    public MyScreen()
    {
    Set the displayed title of the screen
    setTitle ("MyTitle");

    String [] imagePaths = getImagePaths (DEVICE_ALL);
    FlowFieldManager imageFlowField = FlowFieldManager(Manager.VERTICAL_SCROLL | nouveau Manager.VERTICAL_SCROLLBAR);
    If (imagePaths! = null & imagePaths.length > 0) {}
    encodedbitmap = new EncodedImage [imagePaths.length];
    image bitmap = new Bitmap [imagePaths.length];
    imagebitmapField = new BitmapField [imagePaths.length];

    for (int i = 0; i)< imagepaths.length;="" i++)="">
    encodedbitmap [i] = loadEncodedImage ([i] imagePaths);
    [i] bitmap image is scaleImage (encodedbitmap [i], 200, 100);.
    imagebitmapField [i] = new BitmapField(bitmap[i],Field.FOCUSABLE);
    imageFlowField.add (imagebitmapField [i]);
    }
    }
    Add (imageFlowField);

    }

    public Bitmap image scaleImage (EncodedImage img, int width, int height) {}

    int currentWidthF32 = Fixed32.toFP (img.getWidth ());
    int currentHeightF32 = Fixed32.toFP (img.getHeight ());

    If (height == 0) {}
    int requiredWidth = Fixed32.toFP (width);
    int x = Fixed32.div (currentHeightF32, currentWidthF32);
    int y = Fixed32.mul (x, requiredWidth);
    int scaleX = Fixed32.div (currentWidthF32, requiredWidth);
    int scaleY = Fixed32.div (currentHeightF32, y);
    IMG = img.scaleImage32 (scaleX, scaleY);
    } else {}
    int currentWidthFixed32 = Fixed32.toFP (img.getWidth ());
    int currentHeightFixed32 = Fixed32.toFP (img.getHeight ());
    int requiredHeightFixed32 = Fixed32.toFP (height);
    int requiredWidthFixed32 = Fixed32.toFP (width);
    int scaleXFixed32 = Fixed32.div (currentWidthFixed32,
    requiredWidthFixed32);
    int scaleYFixed32 = Fixed32.div (currentHeightFixed32,
    requiredHeightFixed32);
    IMG = img.scaleImage32 (scaleXFixed32, scaleYFixed32);

    }
    Return img.getBitmap ();
    }

    protected EncodedImage loadEncodedImage (String filePath) {}

    FileConnection connection = null;
    Byte [] byteArray = null;
    Image EncodedImage = null;
    Bitmap bitmap image = null;
    Try
    {
    Connection = (FileConnection) Connector.Open (FilePath);
    If (Connection.Exists ())
    {
    byteArray = byte [(int) connection.fileSize (new)];
    InputStream inputStream = connection.openInputStream ();
    inputStream.read (byteArray);
    inputStream.close ();
    image = EncodedImage.createEncodedImage (byteArray, 0, -1);
    }
    Connection.Close;
    }
    catch (System.Exception e)
    {
    System.out.println ("Exception" + try ());
    }
    return image;

    }

    public static String [] getImagePaths (int source) {}

    If get path for all do this recursively
    If (source == DEVICE_ALL) {}
    If (_allImagePaths! = null) {}
    Return _allImagePaths;
    }

    OS6 device Gallery
    String [] os6CameraSDPaths =
    getImagePaths (OS6_SD_CAMERA);

    OS6 Gallery of SD card
    String [] os6CameraPaths =
    getImagePaths (OS6_CAMERA);

    SD card Gallery
    String [] sdCardPaths = getImagePaths (SD_CARD);
    Gallery of the device
    String [] devicePaths =
    getImagePaths (DEVICE_MEM);

    Combine the two in an ImageViewer
    int numOS6CameraSDPaths = os6CameraSDPaths! = null? os6CameraSDPaths.length
    : 0 ;
    int numOS6CameraPaths = os6CameraPaths! = null? os6CameraPaths.length
    : 0 ;
    int numSDCardPaths = sdCardPaths! = null? sdCardPaths.length: 0;
    int numDevicePaths = devicePaths! = null? devicePaths.length: 0;

    int totalNumPaths = numDevicePaths + numSDCardPaths
    + numOS6CameraPaths + numOS6CameraSDPaths;
    If (totalNumPaths > 0) {}
    String of paths [] = new String [totalNumPaths];

    If (os6CameraSDPaths! = null) {}
    System.arraycopy (os6CameraSDPaths, 0, 0, paths)
    numOS6CameraSDPaths);
    }
    If (os6CameraPaths! = null) {}
    System.arraycopy (os6CameraPaths, 0, paths,)
    (numOS6CameraSDPaths, numOS6CameraPaths);
    }
    If (sdCardPaths! = null) {}
    System.arraycopy (sdCardPaths, 0, numOS6CameraSDPaths)
    + numOS6CameraPaths, numSDCardPaths);
    }
    If (devicePaths! = null) {}
    System.arraycopy (devicePaths, 0, paths, numOS6CameraSDPaths)
    + numOS6CameraPaths, + numSDCardPaths,
    numDevicePaths);
    }

    _allImagePaths = sortPaths (paths);

    Return _allImagePaths;
    } else {}
    Returns a null value.
    }
    }

    Set the path to look for
    String imagePath = DEVICE_DIR_PATH;
    If (source == SD_CARD) {}
    imagePath = SD_IMAGE_DIR_PATH;
    }

    If (source == OS6_CAMERA) {}
    imagePath = OS6_CAMERA_PATH;
    }

    If (source == OS6_SD_CAMERA) {}
    imagePath = OS6_SD_CARD_PATH;
    }

    Listed in the directory looking for image files
    ImagePaths vector = new Vector();
    FileConnection imageDir = null;
    try {}
    imageDir = Connector.open (imagePath) (FileConnection);
    If (imageDir! = null) {}
    Enumeration = imageDir.list ();

    imageDir.close ();
    While (enumeration.hasMoreElements ()) {}
    String imageName = (String) enumeration.nextElement ();
    If (isSupported (imageName)) {}
    imagePaths.addElement (imagePath + imageName);
    }
    }
    }
    } catch (Exception e) {}
    XLogger.error (ImagePath.class, "cannot read file:")
    + e.getMessage ());
    } {Finally
    If (imageDir! = null) {}
    try {}
    imageDir.close ();
    } catch (IOException e) {}
    XLogger.error (ImagePath.class, "cannot close the file:")
    + e.getMessage ());
    }
    }
    }

    If there is no images don't return the null value
    If (imagePaths.size)<= 0)="">
    Returns a null value.
    }

    Return the results in an array of strings
    _allImagePaths = new String [imagePaths.size ()];
    imagePaths.copyInto (_allImagePaths);
    Return _allImagePaths;
    }

    private static String [] sortPaths (String [] paths) {}
    Sort the paths of the time, where modified files.
    Class PathAndLastModified {}

    timeStamp long private;
    private String path;

    {} public void setTimeStamp (long timeStamp)
    this.timeStamp = timeStamp;
    }

    {} public void setPath (String path)
    This.Path = path;
    }

    public String GetExtension() {}
    Returns the path;
    }
    }

    Comparator to sort paths
    Comparator pathComparator = new Comparator() {}
    public int compare (Object o1, Object o2) {}
    If (((PathAndLastModified) o1) .timeStamp)< ((pathandlastmodified)o2).timestamp="" )="">
    Return 1;
    } ElseIf (((PathAndLastModified) o1) .timeStamp > .timeStamp (o2 (PathAndLastModified))) {}
    Returns - 1;
    } else {}
    return 0;
    }

    Return (int) (((PathAndLastModified) o2) .timeStamp - .timeStamp (o1 (PathAndLastModified)));
    }
    };

    Add the paths to the vector sorting
    SimpleSortingVector sortedPaths = new SimpleSortingVector();
    sortedPaths.setSortComparator (pathComparator);
    for (int i = 0; i)< paths.length;="" i++)="">
    String filePath = path [i];
    long lastModified = 0;

    FileConnection baseConn = null;
    try {}
    baseConn = (FileConnection), Connector.open (paths [i]);
    lastModified = baseConn.lastModified ();

    PathAndLastModified pathAndLastModified = new PathAndLastModified();
    pathAndLastModified.setPath (filePath);
    pathAndLastModified.setTimeStamp (lastModified);

    sortedPaths.addElement (pathAndLastModified);
    } catch (Exception e) {}
    Do nothing
    } {Finally
    {if(baseConn!=null)}
    try {}
    baseConn.close ();
    } catch (IOException e) {}
    Do nothing
    }
    }
    }
    }
    sortedPaths.reSort ();

    Browse to create an array of sorted paths
    String [] sortedArray = new String [sortedPaths.size ()];
    for (int i = 0; i)
    sortedArray [i] = ((PathAndLastModified) sortedPaths.elementAt (i)) .getPath ();
    }

    Return sortedArray;
    }

    private static Boolean isSupported (image String) {}
    Make sure that the image is of the correct type
    If (image == null) {}
    Returns false;
    }
    check the directory
    If (image.indexOf("/") > = 0) {}
    Returns false;
    }

    int delimiterIndex = image.indexOf(".");
    If (delimiterIndex ==-1) {}
    probably a directory
    Returns false;
    }

    the text is a list of extensions supported
    String [] extensions = {".jpg", ".jpeg"};
    for (int i = 0; i)< extensions.length;="" i++)="">
    If (image.length () > extensions [i] .length ()) {}
    Dim ext = image.substring (image.length)
    (-extensions [i] .length ());
    If (ext.equalsIgnoreCase (extensions [i])) {}
    Returns true;
    }
    }
    }
    Returns false;
    }
    }

    my suggestion was supposed to replace navigationclick on-screen.
    If you want to ignore it for the field that you do not have to use getLeafFieldWithFocus.

    I suggest that you think your code, don't write things and try to operate, fist think about something and then implement.
    our projects at the University were generally 80% design, 20% of coding - it was strange at first, but it produced a lot more code.

  • Overlap two images, ordinary java works, and not in BlackBerry JDE 5

    I have an application for swing of simple java that takes two images and overlaps the other. While trying to this port in JDE5, I got out there is no class BufferedImage in the api of BB, but a similar class of the Bitmap. It's brought to BB mixing function is unable to produce an image that overlap. It shows a blank white screen.

    Here's the plain java function

    public BufferedImage blend( BufferedImage bi1, BufferedImage bi2,            double weight )   {     if (bi1 == null)          throw new NullPointerException("bi1 is null");
    
          if (bi2 == null)          throw new NullPointerException("bi2 is null");
    
          int width = bi1.getWidth();       if (width != bi2.getWidth())          throw new IllegalArgumentException("widths not equal");
    
         int height = bi1.getHeight();     if (height != bi2.getHeight())
    
              throw new IllegalArgumentException("heights not equal");
    
            BufferedImage bi3 = new BufferedImage(width, height,              BufferedImage.TYPE_INT_RGB);      int[] rgbim1 = new int[width];        int[] rgbim2 = new int[width];        int[] rgbim3 = new int[width];
    
          for (int row = 0; row < height; row++)     {         bi1.getRGB(0, row, width, 1, rgbim1, 0, width);           bi2.getRGB(0, row, width, 1, rgbim2, 0, width);
    
             for (int col = 0; col < width; col++)          {             int rgb1 = rgbim1[col];               int r1 = (rgb1 >> 16) & 255;                int g1 = (rgb1 >> 8) & 255;             int b1 = rgb1 & 255;
    
                    int rgb2 = rgbim2[col];               int r2 = (rgb2 >> 16) & 255;                int g2 = (rgb2 >> 8) & 255;             int b2 = rgb2 & 255;
    
                    int r3 = (int) (r1 * weight + r2 * (1.0 - weight));               int g3 = (int) (g1 * weight + g2 * (1.0 - weight));               int b3 = (int) (b1 * weight + b2 * (1.0 - weight));               rgbim3[col] = (r3 << 16) | (g3 << 8) | b3;            }
    
               bi3.setRGB(0, row, width, 1, rgbim3, 0, width);       }
    
           return bi3;   } 
    

    Here's the java function of BB

      public Bitmap blend( Bitmap bi1, Bitmap  bi2,                      double weight )        {
    
                  if (bi1 == null)                       throw new NullPointerException("bi1 is null");
    
                    if (bi2 == null)                       throw new NullPointerException("bi2 is null");
    
                    int width = bi1.getWidth();            if (width != bi2.getWidth())                   throw new IllegalArgumentException("widths not equal");
    
                   int height = bi1.getHeight();          if (height != bi2.getHeight())
    
                            throw new IllegalArgumentException("heights not equal");
    
             Bitmap bi3 = new Bitmap(width, height);         int[] rgbim1 = new int[width];         int[] rgbim2 = new int[width];         int[] rgbim3 = new int[width];
    
                    for (int row = 0; row < height; row++)         {
    
                           bi1.getARGB(rgbim1,0,width,0,row, width,1);                       bi2.getARGB(rgbim2,0,width,0,row, width,1); 
    
                           for (int col = 0; col < width; col++)                  {                              int rgb1 = rgbim1[col];                                int r1 = (rgb1 >> 16) & 255;                           int g1 = (rgb1 >> 8) & 255;                            int b1 = rgb1 & 255;
    
                              int rgb2 = rgbim2[col];                                int r2 = (rgb2 >> 16) & 255;                           int g2 = (rgb2 >> 8) & 255;                            int b2 = rgb2 & 255;
    
                              int r3 = (int) (r1 * weight + r2 * (1.0 - weight));                            int g3 = (int) (g1 * weight + g2 * (1.0 - weight));                            int b3 = (int) (b1 * weight + b2 * (1.0 - weight));                            rgbim3[col] = (r3 << 16) | (g3 << 8) | b3;                     }
    
                         bi3.setARGB(rgbim3, 0, width, 0,  row,width, 1);
    
                    }
    
                 return bi3;    }
    

    The weight of the arg is a value from 1 to 100.

    For reference, the full plain java source

    /* * To change this template, choose Tools | Templates * and open the template in the editor. */
    
    package imagetest;
    
    /** * * @author COMPUTER */// Blender1.java
    
    import java.awt.*;import java.awt.image.*;
    
    import javax.swing.*;import javax.swing.event.*;
    
    /** * This class describes and contains the entry point to an application that * demonstrates the blending transition. */
    
    public class Blender1 extends JFrame{  /**    *     */   private static final long serialVersionUID = 1L;
    
        /**    * Construct Blender1 GUI.     */
    
     public Blender1() {     super("Blender #1");      setDefaultCloseOperation(EXIT_ON_CLOSE);
    
            // Load first image from JAR file and draw image into a buffered image.
    
         ImageIcon ii1 = new ImageIcon(getClass().getResource("x.png"));       final BufferedImage bi1;      bi1 = new BufferedImage(ii1.getIconWidth(), ii1.getIconHeight(),              BufferedImage.TYPE_INT_RGB);      Graphics2D g2d = bi1.createGraphics();        int h = ii1.getImage().getHeight(null);       System.out.println("Blender1.Blender1()--------> height :" + h);       g2d.drawImage(ii1.getImage(), 0, 0, null);        g2d.dispose();
    
          // Load second image from JAR file and draw image into a buffered image.
    
            ImageIcon ii2 = new ImageIcon(getClass().getResource("y.png"));       final BufferedImage bi2;      bi2 = new BufferedImage(ii2.getIconWidth(), ii2.getIconHeight(),              BufferedImage.TYPE_INT_RGB);      g2d = bi2.createGraphics();       int h2 = ii2.getImage().getHeight(null);      System.out.println("Blender1.Blender1()--------> height :" + h2);      g2d.drawImage(ii2.getImage(), 0, 0, null);        g2d.dispose();
    
          // Create an image panel capable of displaying entire image. The widths       // of both images and the heights of both images must be identical.
    
         final ImagePanel ip = new ImagePanel();       ip.setPreferredSize(new Dimension(ii1.getIconWidth(), ii1             .getIconHeight()));       getContentPane().add(ip, BorderLayout.NORTH);
    
           // Create a slider for selecting the blending percentage: 100% means      // show all of first image; 0% means show all of second image.
    
          final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 100);      slider.setMinorTickSpacing(5);        slider.setMajorTickSpacing(10);       slider.setPaintTicks(true);       slider.setPaintLabels(true);      slider.setLabelTable(slider.createStandardLabels(10));        slider.setInverted(true);     ChangeListener cl;        cl = new ChangeListener()     {         public void stateChanged( ChangeEvent e )         {             // Each time the user adjusts the slider, obtain the new              // blend percentage value and use it to blend the images.
    
                   int value = slider.getValue();                ip.setImage(blend(bi1, bi2, value / 100.0));          }     };        slider.addChangeListener(cl);     getContentPane().add(slider, BorderLayout.SOUTH);
    
           // Display the first image, which corresponds to a 100% blend     // percentage.
    
          ip.setImage(bi1);
    
           pack();       setVisible(true); }
    
       /**    * Blend the contents of two BufferedImages according to a specified weight.   *     * @param bi1  *            first BufferedImage  * @param bi2  *            second BufferedImage     * @param weight   *            the fractional percentage of the first image to keep     *     * @return new BufferedImage containing blended contents of BufferedImage  *         arguments   */
    
     public BufferedImage blend( BufferedImage bi1, BufferedImage bi2,         double weight )   {     if (bi1 == null)          throw new NullPointerException("bi1 is null");
    
          if (bi2 == null)          throw new NullPointerException("bi2 is null");
    
          int width = bi1.getWidth();       if (width != bi2.getWidth())          throw new IllegalArgumentException("widths not equal");
    
         int height = bi1.getHeight();     if (height != bi2.getHeight())
    
              throw new IllegalArgumentException("heights not equal");
    
            BufferedImage bi3 = new BufferedImage(width, height,              BufferedImage.TYPE_INT_RGB);      int[] rgbim1 = new int[width];        int[] rgbim2 = new int[width];        int[] rgbim3 = new int[width];
    
          for (int row = 0; row < height; row++)     {         bi1.getRGB(0, row, width, 1, rgbim1, 0, width);           bi2.getRGB(0, row, width, 1, rgbim2, 0, width);
    
             for (int col = 0; col < width; col++)          {             int rgb1 = rgbim1[col];               int r1 = (rgb1 >> 16) & 255;                int g1 = (rgb1 >> 8) & 255;             int b1 = rgb1 & 255;
    
                    int rgb2 = rgbim2[col];               int r2 = (rgb2 >> 16) & 255;                int g2 = (rgb2 >> 8) & 255;             int b2 = rgb2 & 255;
    
                    int r3 = (int) (r1 * weight + r2 * (1.0 - weight));               int g3 = (int) (g1 * weight + g2 * (1.0 - weight));               int b3 = (int) (b1 * weight + b2 * (1.0 - weight));               rgbim3[col] = (r3 << 16) | (g3 << 8) | b3;            }
    
               bi3.setRGB(0, row, width, 1, rgbim3, 0, width);       }
    
           return bi3;   }
    
       /**    * Application entry point.    *     * @param args     *            array of command-line arguments  */
    
     public static void main( String[] args )  {     Runnable r = new Runnable()       {         public void run()         {             // Create Blender1's GUI on the event-dispatching             // thread.
    
                  new Blender1();           }     };        EventQueue.invokeLater(r);    }}
    
    /** * This class describes a panel that displays a BufferedImage's contents. */
    
    class ImagePanel extends JPanel{ /**    *     */   private static final long serialVersionUID = 4977990666209629996L;    private BufferedImage bi;
    
       /**    * Specify and paint a new BufferedImage.  *     * @param bi   *            BufferedImage whose contents are to be painted   */
    
     void setImage( BufferedImage bi ) {     this.bi = bi;     repaint();    }
    
       /**    * Paint the image panel.  *     * @param g    *            graphics context used to paint the contents of the current   *            BufferedImage    */
    
     public void paintComponent( Graphics g )  {     if (bi != null)       {         Graphics2D g2d = (Graphics2D) g;          g2d.drawImage(bi, null, 0, 0);        } }}
    

    Full java BB source

    /* * ImageScreen.java * * © ,  * Confidential and proprietary. */
    
    package src;
    
    /** *  */
    
    import java.io.OutputStream;import javax.microedition.io.Connector;import javax.microedition.io.file.FileConnection;import net.rim.device.api.system.Bitmap;import net.rim.device.api.ui.Field;import net.rim.device.api.ui.FieldChangeListener;import net.rim.device.api.ui.UiApplication;import net.rim.device.api.ui.component.BitmapField;import net.rim.device.api.ui.component.ButtonField;import net.rim.device.api.ui.component.Dialog;import net.rim.device.api.ui.component.LabelField;import net.rim.device.api.ui.container.HorizontalFieldManager;import net.rim.device.api.ui.container.MainScreen;import net.rim.device.api.ui.component.GaugeField;/** * The main screen to display an image taken from the camera demo. */public final class ImageScreen extends MainScreen{    /** The down-scaling ratio applied to the snapshot Bitmap */    private static final int IMAGE_SCALING = 7;
    
        /** The base file name used to store pictures */    private static final String FILE_NAME = System.getProperty("fileconn.dir.photos") + "IMAGE";
    
        /** The extension of the pictures to be saved */    private static final String EXTENSION = ".bmp";
    
        /** A counter for the number of snapshots taken */    private static int _counter;    Bitmap image1,image2; BitmapField imageField;     /** A reference to the current screen for listeners */    private ImageScreen _imageScreen;
    
       /**    * Constructor    * @param raw A byte array representing an image    */    public ImageScreen( final byte[] raw1,final byte[] raw2 )    {        // A reference to this object, to be used in listeners        _imageScreen = this;
    
            setTitle("Blend and Save");
    
            // Convert the byte array to a Bitmap image        image1 = Bitmap.createBitmapFromBytes( raw1, 0, -1, 1 );        image2 = Bitmap.createBitmapFromBytes( raw2, 0, -1, 1 );        // Create two field managers to center the screen's contents        HorizontalFieldManager hfm1 = new HorizontalFieldManager( Field.FIELD_HCENTER );        HorizontalFieldManager hfm2 = new HorizontalFieldManager( Field.FIELD_HCENTER );        HorizontalFieldManager hfm3 = new HorizontalFieldManager( Field.FIELD_HCENTER );        // Create the field that contains the image//blend(image1, image2, 50/ 100.0)        imageField = new BitmapField(blend(image1, image2, 50/ 100.0) ){
    
               public int getPreferredWidth(){ return 250;}           public int getPreferredHeight(){ return 150;}
    
             };
    
            hfm1.add( imageField ); 
    
            GaugeField scroller = new GaugeField("Adjust (alt + < >)",0,100,50,Field.EDITABLE | Field.FOCUSABLE);        //scroller.setBackground( net.rim.device.api.ui.decor.BackgroundFactory.createSolidBackground(0x00000000));          scroller.setChangeListener( new GaugeFieldListener() );         hfm2.add(scroller);         // Create the SAVE button which returns the user to the main camera        // screen and saves the picture as a file.        ButtonField photoButton = new ButtonField( "Save" );        photoButton.setChangeListener( new SaveListener(raw1,raw2) );        hfm3.add(photoButton);
    
            // Create the CANCEL button which returns the user to the main camera        // screen without saving the picture.        ButtonField cancelButton = new ButtonField( "Cancel" );        cancelButton.setChangeListener( new CancelListener() );        hfm3.add(cancelButton);
    
            // Add the field managers to the screen        add( hfm1 );        add( hfm2 );        add( hfm3 );scroller.setFocus();//scroller.setValue(50);    }    public Bitmap blend( Bitmap bi1, Bitmap  bi2,                      double weight )        {
    
                  if (bi1 == null)                       throw new NullPointerException("bi1 is null");
    
                    if (bi2 == null)                       throw new NullPointerException("bi2 is null");
    
                    int width = bi1.getWidth();            if (width != bi2.getWidth())                   throw new IllegalArgumentException("widths not equal");
    
                   int height = bi1.getHeight();          if (height != bi2.getHeight())
    
                            throw new IllegalArgumentException("heights not equal");
    
             Bitmap bi3 = new Bitmap(width, height);         int[] rgbim1 = new int[width];         int[] rgbim2 = new int[width];         int[] rgbim3 = new int[width];
    
                    for (int row = 0; row < height; row++)         {            // bi -> int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) 
    
                 // bit - > int[] argbData, int offset, int scanLength, int x, int y, int width, int height) 
    
                           bi1.getARGB(rgbim1,0,width,0,row, width,1);//  row, width, 1, , 0, width);                       bi2.getARGB(rgbim2,0,width,0,row, width,1); 
    
                           //bi1.getRGB(0, row, width, 1, rgbim1, 0, width);                       //bi2.getRGB(0, row, width, 1, rgbim2, 0, width);
    
                           for (int col = 0; col < width; col++)                  {                              int rgb1 = rgbim1[col];                                int r1 = (rgb1 >> 16) & 255;                           int g1 = (rgb1 >> 8) & 255;                            int b1 = rgb1 & 255;
    
                              int rgb2 = rgbim2[col];                                int r2 = (rgb2 >> 16) & 255;                           int g2 = (rgb2 >> 8) & 255;                            int b2 = rgb2 & 255;
    
                              int r3 = (int) (r1 * weight + r2 * (1.0 - weight));                            int g3 = (int) (g1 * weight + g2 * (1.0 - weight));                            int b3 = (int) (b1 * weight + b2 * (1.0 - weight));                            rgbim3[col] = (r3 << 16) | (g3 << 8) | b3;                     }                    //bi -> int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize)                     //bit -> (int[] data, int offset, int scanLength, int left, int top, int width, int height)                      bi3.setARGB(rgbim3, 0, width, 0,  row,width, 1);
    
                        // bi3.setRGB(0, row, width, 1, rgbim3, 0, width);                }
    
                 return bi3;    }
    
       /**    * Handles trackball click events    * @see net.rim.device.api.ui.Screen#invokeAction(int)    */       protected boolean invokeAction(int action)    {        boolean handled = super.invokeAction(action); 
    
            if(!handled)        {            switch(action)            {                case ACTION_INVOKE: // Trackball click.                {                                 return true;                }            }        }                return handled;              }
    
     /**    * A listener used for the "Save" button    */    private class GaugeFieldListener implements FieldChangeListener    {        public void fieldChanged(Field field, int context)        {          int value =  ((GaugeField)field).getValue(); if (value==0){return;}          imageField.setBitmap( blend(image1, image2, value/ 100.0) );          ((GaugeField)field).setLabel("Adjust (alt + < >)"+value);        }    }   /**    * A listener used for the "Save" button    */    private class SaveListener implements FieldChangeListener    {        /** A byte array representing an image */        private byte[] _raw1,_raw2;
    
           /**        * Constructor.        * @param raw A byte array representing an image        */        SaveListener(byte[] raw1,byte[] raw2)        {            _raw1 = raw1;            _raw2 = raw2;        }
    
           /**        * Saves the image as a file in the BlackBerry filesystem        */        public void fieldChanged(Field field, int context)        {            try            {                       // Create the connection to a file that may or                // may not exist.                FileConnection file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );
    
                    // If the file exists, increment the counter until we find                // one that hasn't been created yet.                while( file.exists() )                {                    file.close();                    ++_counter;                    file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );                }
    
                    // We know the file doesn't exist yet, so create it                file.create();
    
                    // Write the image to the file                OutputStream out = file.openOutputStream();                out.write(_raw1);
    
                    // Close the connections                out.close();                file.close();            }            catch(Exception e)            {                Dialog.alert( "ERROR " + e.getClass() + ":  " + e.getMessage() );            }
    
                // Inform the user where the file has been saved            Dialog.inform( "Saved to " + FILE_NAME + _counter + EXTENSION );
    
                // Increment the image counter            ++_counter;
    
                // Return to the main camera screen            UiApplication.getUiApplication().popScreen( _imageScreen );        }    }
    
       /**    * A listener used for the "Cancel" button    */    private class CancelListener implements FieldChangeListener    {       /**        * Return to the main camera screen        */        public void fieldChanged(Field field, int context)        {            UiApplication.getUiApplication().popScreen( _imageScreen );        }    }}
    

    Yes, your original code:

    for (int col = 0; col < width; col++){int rgb1 = rgbim1[col];int r1 = (rgb1 >> 16) & 255;int g1 = (rgb1 >> 8) & 255;int b1 = rgb1 & 255;
    
    int rgb2 = rgbim2[col];int r2 = (rgb2 >> 16) & 255;int g2 = (rgb2 >> 8) & 255;int b2 = rgb2 & 255;
    
    int r3 = (int) (r1 * weight + r2 * (1.0 - weight));int g3 = (int) (g1 * weight + g2 * (1.0 - weight));int b3 = (int) (b1 * weight + b2 * (1.0 - weight));rgbim3[col] = (r3 << 16) | (g3 << 8) | b3;}
    

    Labour Code:

    for (int col = 0; col < width; col++)
    {
    int rgb1 = rgbim1[col];
    int a1 = (rgb1 >> 24) & 255;
    int r1 = (rgb1 >> 16) & 255;
    int g1 = (rgb1 >> 8) & 255;
    int b1 = rgb1 & 255;
    
    int rgb2 = rgbim2[col];
    int a2 = (rgb2 >> 24) & 255;
    int r2 = (rgb2 >> 16) & 255;
    int g2 = (rgb2 >> 8) & 255;
    int b2 = rgb2 & 255;
    
    int a3 = (int) (a1 * weight + a2 * (1.0 - weight));
    int r3 = (int) (r1 * weight + r2 * (1.0 - weight));
    int g3 = (int) (g1 * weight + g2 * (1.0 - weight));
    int b3 = (int) (b1 * weight + b2 * (1.0 - weight));
    rgbim3[col] = (a3 << 24) | (r3 << 16) | (g3 << 8) | b3;
    }
    
  • Button image

    Hello I'm using image button focus and unfocus. My problem is that when Gets the focus on the image and get unfoucs of image, it will display blue color border. I don't want this blue border.

    I don't know how I should delete that? I enclose below class customeImageButton. I don't want on each edge of the blue side on the image button. Plese help me.

    package com.api;
    
    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.ui.Graphics;
    import net.rim.device.api.ui.component.ButtonField;
    
    /* Customized ImageButton */
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Class Name      :       ColorManager
    //Created On      :       14/11/2011
    //Created By      :       Ajay Patil
    //Purpose         :       This class is for Button field with a bitmap as its label
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    /**
     * Button field with a bitmap as its label.
     */
    public class CustomImgButtonField extends ButtonField
    {
            private Bitmap bitmap;
            private Bitmap bitmapHighlight;
            private boolean highlighted = false;
    
            /**
             * Instantiates a new bitmap button field.
             *
             * @param bitmap the bitmap to use as a label
             */
            public CustomImgButtonField(Bitmap bitmap, Bitmap bitmapHighlight)
            {
                this(bitmap, bitmapHighlight, ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER|ButtonField.FIELD_VCENTER);
            }
    
            public CustomImgButtonField(Bitmap bitmap, Bitmap bitmapHighlight, long style)
            {
                super(style);
                this.bitmap = bitmap;
                this.bitmapHighlight = bitmapHighlight;
            }
    
            /* (non-Javadoc)
             * @see net.rim.device.api.ui.component.ButtonField#layout(int, int)
             */
            protected void layout(int width, int height)
            {
                    setExtent(getPreferredWidth(), getPreferredHeight());
            }
    
            /* (non-Javadoc)
             * @see net.rim.device.api.ui.component.ButtonField#getPreferredWidth()
             */
            public int getPreferredWidth() {
                    return bitmap.getWidth();
            }
    
            /* (non-Javadoc)
             * @see net.rim.device.api.ui.component.ButtonField#getPreferredHeight()
             */
            public int getPreferredHeight() {
                    return bitmap.getHeight();
            }
            /* (non-Javadoc)
             * @see net.rim.device.api.ui.component.ButtonField#paint(net.rim.device.api.ui.Graphics)
             */
            protected void paint(Graphics graphics) {
                    super.paint(graphics);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    Bitmap b = bitmap;
                    if (highlighted)
                        b = bitmapHighlight;
                    graphics.drawBitmap(0, 0, width, height, b, 0, 0);
            }
            protected void onFocus(int direction)
            {
                this.setHighlight(true); super.onFocus(direction);
            }
            protected void onUnfocus()
            {
                this.setHighlight(false);
                super.onUnfocus();
            }
            public void setHighlight(boolean highlight)
            {
                this.highlighted = highlight;
            }
    }
    

    I have an extended bitmapfield which reacts on the navigationclick and key, related to his fieldchangelistener. works well for years.

    If you are unable to apply it yourself, this can help you:
    http://supportforums.BlackBerry.com/T5/Java-development/implement-advanced-buttons-fields-and-manage...

  • Change on the fly application background image

    My main application screen has a background image, set (it is abbreviated):

    Class BBScreen extends screen implements {FieldChangeListener}

    public BBScreen()

    {

    Super (Manager.NO_VERTICAL_SCROLL);

    setTitle ("my app");

    BM1 = Bitmap.getBitmapResource (...);

    vfm0 = new VerticalFieldManager (...) {

    public void paint (Graphics graphics)

    {

    graphics.drawBitmap (..., bm1,...);

    Super.paint (graphics);

    }

    };

    Add (vfm0);

    }

    }

    However at some point during execution, I want the background image of the bm1 to bm2.  How to set the new picture and that the painting occurs?  Thanks for the pointers.  FD

    Try something like this:

    public class BBScreen extends MainScreen implements FieldChangeListener{    Bitmap bm1 = Bitmap.getBitmapResource("image1.png");    Bitmap bm2 = Bitmap.getBitmapResource("image2.png");    Bitmap mainBitmap;    public TestScreen()     {        super(Manager.NO_VERTICAL_SCROLL);        setTitle( "My Title");           mainBitmap = bm1;        VerticalFieldManager vfm0 = new VerticalFieldManager(...)        {            public void paint(Graphics graphics)            {                graphics.drawBitmap(.., mainBitmap, ...);                super.paint(graphics);            }         };        ButtonField btn = new ButtonField("Change Background");        btn.setChangeListener(this);        vfm0.add(btn);        add(vfm0);        }    public void fieldChanged(Field field, int context)     {        mainBitmap = bm2;       this.invalidate();   }}
    

    Concerning

    Bika

  • On the Images of background and layouts

    Hello everyone - two quick questions that are virtually related to each other.

    First of all, is it possible to make a fixed image against canvas (similar to the background position: fixed in CSS attribute). I have the following code - the image is located in the back while a text is superimposed on it. I want the image remains fixed while the user scrolls the text. I could not find a method to keep the fixed image.

    HorizontalFieldManager horizontalFieldManager = new HorizontalFieldManager(HorizontalFieldManager.USE_ALL_WIDTH | HorizontalFieldManager.USE_ALL_HEIGHT){
        // override pain method to create the background image
        public void paint(Graphics graphics) {
            // draw the background image
            graphics.drawBitmap(0, 0, deviceWidth, deviceHeight, _backgroundBitmap, 0, 0);
            super.paint(graphics);
        }
    };
    

    Second, is a way to position a field/label button on the screen absolutely? I read on setChildPosition() but I don't think that's what I was looking for. Basically, I want to put in place the following code to show to the bottom right of the screen with some of the background image. I imagine that there is a way to do it, but it eludes me right now.

    _playButton = new WhaleAppButtonClass("stream1button_PLAY.png", Field.FOCUSABLE);
    

    Thank you in advance!

    Hello

    On the background image, you can try something like this:

    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.*;
    import net.rim.device.api.system.*;
    
    public class TestScreen extends MainScreen
    {
    
        private VerticalFieldManager mainManager;
        private VerticalFieldManager subManager;
        private Bitmap _backgroundBitmap = Bitmap.getBitmapResource("sunset.png");
    
        private int deviceWidth = Display.getWidth();
        private int deviceHeight = Display.getHeight();
    
        public TestScreen()
        {
            super(NO_VERTICAL_SCROLL);
    
            //this manager is used for the static background image
            mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
            {
                public void paint(Graphics graphics)
                {
                    graphics.clear();
                    graphics.drawBitmap(0, 0, deviceWidth, deviceHeight, _backgroundBitmap, 0, 0);
                    super.paint(graphics);
                }
            };
    
            //this manger is used for adding the componentes
            subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
            {
                protected void sublayout( int maxWidth, int maxHeight )
                {
                    int displayWidth = deviceWidth;
                    int displayHeight = deviceHeight;
    
                    super.sublayout( displayWidth, displayHeight);
                    setExtent( displayWidth, displayHeight);
                }
            };
    
            /// add your component to this subManager/////////
            subManager.add(new ButtonField("Button1"));
            subManager.add(new ButtonField("Button2"));
            subManager.add(new ButtonField("Button3"));
            subManager.add(new ButtonField("Button4"));
            subManager.add(new ButtonField("Button5"));
            subManager.add(new ButtonField("Button6"));
            subManager.add(new ButtonField("Button7"));
            subManager.add(new ButtonField("Button8"));
            subManager.add(new ButtonField("Button9"));
            subManager.add(new ButtonField("Button10"));
            subManager.add(new ButtonField("Button11"));
            subManager.add(new ButtonField("Button12"));
            subManager.add(new ButtonField("Button13"));
            subManager.add(new ButtonField("Button14"));
            subManager.add(new ButtonField("Button15"));
            ///////////////////////////////////////////////////
    
            //add subManager over the mainManager
            mainManager.add(subManager);
    
            //finally add the mainManager over the screen
            this.add(mainManager);       
    
        }
    }
    

    And on the definition of the elements in X and there contact information:

    There is no direct method to place items in X, Y coordinates.

    In this case you will need a custom layout manager.

    This article will help you wtitting Manager of custom page layout.

    http://www.BlackBerry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800505/800508/...

    Concerning

    Bika

  • Buttons with images, by setting the size?

    Hello

    I use the following code to add images to the buttons. However, I got some of the buttons out of the view from the window! What can I add to make them fit on the display window?

    MORE: I want them to be on the Center vertically and horizontally. Let's say I have 15 buttons, I want 3 each line. And in the center of the screen?

    And finally, is it possible to make the button selected by default as NULL? Then, key 1 is not selected at the beginning as shown in the picture as an attachment!

    * Image attached *.

    Thanks in advance

    Code:

    public class BitmapButtonField extends ButtonField {
            private Bitmap bitmap;
            private Bitmap bitmapHighlight;
            private boolean highlighted = false;
    
            public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight) {
                this(bitmap, bitmapHighlight, ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER|ButtonField.FIELD_VCENTER);
            }
    
            public BitmapButtonField(Bitmap bitmap, Bitmap bitmapHighlight, long style) {
                super(style);
                this.bitmap = bitmap;
                this.bitmapHighlight = bitmapHighlight;
            }
    
            protected void layout(int width, int height) {
                    setExtent(getPreferredWidth(), getPreferredHeight());
            }
    
            public int getPreferredWidth() {
                    return bitmap.getWidth();
            }
    
            public int getPreferredHeight() {
                    return bitmap.getHeight();
            }
    
            protected void paint(Graphics graphics) {
                    super.paint(graphics);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    Bitmap b = bitmap;
                    if (highlighted)
                        b = bitmapHighlight;
                    graphics.drawBitmap(0, 0, width, height, b, 0, 0);
            }
    }
    

    SOLVED

    I solved by:

    1 - scaling images with display:

            public int getPreferredWidth() {
                    return Display.getWidth()/6;
            }
    
            public int getPreferredHeight() {
                    return Display.getHeight()/6;
            }
    

    2 - using HorizontalFieldManager:

    HorizontalFieldManager(FIELD_HCENTER);
    

    Thank you

  • Download the image as object

    HII, please how to download image from the server as an image object? and how to do it?

    The following code example downloads a picture from the Internet and displays it on a screen.

    public final class ImageDownloadTestScreen extends MainScreen {
        static LabelField label = new LabelField();
        static BitmapField img = new BitmapField();
    
        public ImageDownloadTestScreen() {
    
            ButtonField btnDownload = new ButtonField("Download Image", ButtonField.CONSUME_CLICK);
            btnDownload.setChangeListener(new FieldChangeListener() {
                public void fieldChanged(Field field, int context) {
                    String url = "http://worldwide.blackberry.com/blackberrycurve/8900/8900_series_device.jpg";
                    label.setText("Start to download...");
                    ImageDownloadTestScreen.download(url);
                }
            });
            add(btnDownload);
            add(label);
            add(img);
        }
    
        protected static void download(final String url) {
            new Thread(new Runnable() {
                public void run() {
                    // obtain ConnectionFactory object
                    ConnectionFactory cf = new ConnectionFactory();
                    // obtain ConnectionDescriptor object
                    ConnectionDescriptor cd = cf.getConnection(url);
                    if (cd != null) {// connect successful
                        // get the connection
                        HttpConnection conn = null;
                        try {
                            conn = (HttpConnection) cd.getConnection();
                            // get the data stream
                            InputStream in = conn.openInputStream();
                            // download data
                            byte[] data = IOUtilities.streamToBytes(in);
                            // write data into an EncodedImage object
                            EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
                            // display the image in screen
                            synchronized (Application.getEventLock()) {
                                img.setImage(image);
                                label.setText("Download...Done!");
                            }
                        } catch (IOException e) {
                            synchronized (Application.getEventLock()) {
                                label.setText("Download...Error! " + e.getMessage());
                            }
                        }finally{
                            if(conn != null){
                                try {
                                    conn.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        synchronized (Application.getEventLock()) {
                            label.setText("Download...Error! Could not connect!");
                        }
                    }
                }
            }).start();
        }
    }
    

Maybe you are looking for