Designing a slot machine in blackberry - blackberry

I am a Blackberry java developer. I am trying to develop a simple slot machine logic. I am new to animated graphics etc in blackberry. So, can anyone tell me how to design a simple slot machine where on pressing a button the images in 3 blocks must start rotating and after it stops the prizes will be displayed according to the pics. So can u plz help me with some samples or tutorials of how to do it...
Edit: I am developing it just as fun application that doesnt involve any money transactions. So, any Blackberry developers plz guide me how to achieve the task and to spin the three images on click of a button...

This is a simple example but you will have to deal with decoration, smooth rolling etc yourself.
Let's say you have 6 images 70x70.
Simple BitmapField extension to paint current slot image, half of image above and half of image below:
class SlotField extends BitmapField {
Bitmap bmp1 = Bitmap.getBitmapResource("img1.png");
Bitmap bmp2 = Bitmap.getBitmapResource("img2.png");
Bitmap bmp3 = Bitmap.getBitmapResource("img3.png");
Bitmap bmp4 = Bitmap.getBitmapResource("img4.png");
Bitmap bmp5 = Bitmap.getBitmapResource("img5.png");
Bitmap bmp6 = Bitmap.getBitmapResource("img6.png");
Bitmap[] bmps = new Bitmap[] { bmp1, bmp2, bmp3, bmp4, bmp5, bmp6 };
int mPos = 0;
public SlotField(int position) {
mPos = position;
}
public int getBitmapHeight() {
return bmp1.getHeight() * 2;
}
public int getBitmapWidth() {
return bmp1.getWidth();
}
protected void layout(int width, int height) {
setExtent(getBitmapWidth(), getBitmapHeight());
}
int getNextPos() {
if (mPos == bmps.length - 1) {
return 0;
} else
return mPos + 1;
}
int getPrevPos() {
if (mPos == 0) {
return bmps.length - 1;
} else
return mPos - 1;
}
protected void paint(Graphics g) {
Bitmap hImg = bmps[getPrevPos()];
Bitmap mImg = bmps[mPos];
Bitmap lImg = bmps[getNextPos()];
g.drawBitmap(0, 0, 70, 35, hImg, 0, 35);
g.drawBitmap(0, 35, 70, 70, mImg, 0, 0);
g.drawBitmap(0, 105, 70, 35, lImg, 0, 0);
}
}
Now put these fields on screen and animate with timer:
class MainScr extends MainScreen {
SlotField slot1 = new SlotField(0);
SlotField slot2 = new SlotField(3);
SlotField slot3 = new SlotField(5);
boolean running = false;
public MainScr() {
HorizontalFieldManager hField = new HorizontalFieldManager();
add(hField);
hField.add(slot1);
hField.add(slot2);
hField.add(slot3);
ButtonField btnRoll = new ButtonField("Roll");
btnRoll.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!running)
rollSlots();
}
});
add(btnRoll);
}
void rollSlots() {
Timer timer = new Timer();
final Random rnd = new Random();
TimerTask ttask1 = new TimerTask() {
int cycle = 0;
public void run() {
slot1.mPos = slot1.getNextPos();
invalidate();
cycle++;
if (cycle >= 100+rnd.nextInt(6))
cancel();
}
};
TimerTask ttask2 = new TimerTask() {
int cycle = 0;
public void run() {
slot2.mPos = slot2.getNextPos();
invalidate();
cycle++;
if (cycle >= 100+rnd.nextInt(6))
cancel();
}
};
TimerTask ttask3 = new TimerTask() {
int cycle = 0;
public void run() {
slot3.mPos = slot3.getNextPos();
invalidate();
cycle++;
if (cycle >= 100+rnd.nextInt(6))
cancel();
}
};
timer.schedule(ttask1, 0, 50);
timer.schedule(ttask2, 200, 50);
timer.schedule(ttask3, 400, 50);
}
}
alt text http://img534.imageshack.us/img534/2172/slots.jpg
For UI functionality read
Blackberry User Interface Design - Customizable UI?
and
Blackberry - fields layout animation

The simulation of mechanical reels on a gaming machine is protected by United States Patent 7452276. The patent web page has links to 40 other US and international patents that you would have to investigate before you could start developing your software.
After you received permission from all of the different US and international patent holders to develop your software, you would develop a long .gif strip with the different images that you quickly move down in three or more positions. Your software would have to distort the top and bottom edges of the visible portions of the .gif strip to give the appearance of a mechanical slot wheel.

Related

Remove raised effect in blackberry objectchoicefield and buttonfield

I am trying to achieve a flat look for blackberry controls, namely objectchoicefield and buttonfield.
The following code does not seem to do the trick. (The width setting does work, but not the border setting.)
public static ObjectChoiceField GetDropdownList(String label, String[] data)
{
ObjectChoiceField ocf = new ObjectChoiceField(null, data, 0, Field.FIELD_LEFT);
ocf.setBorder(BorderFactory.createSimpleBorder(new XYEdges(0,0,0,0)));
ocf.setMinimalWidth(Display.getWidth()-61);
return ocf;
}
I get the same appearance with or without the setBorder statement. Basically I do not want any 3D look or shadow or shine or rounded corners.
Thanks
This might not do everything you want, but you can try looking at this custom ObjectChoiceField that I built for OS 4.6 and lower devices. I wanted to add a glossy, 3D look, but you could change the custom paint() code I used to make a simpler, flatter look.
Taking my example, changing the rounded corner radius to 1, and removing the call to super.paint(g) gives something like this:
public class CustomChoiceField extends ObjectChoiceField {
private int _bgWidth = 0;
private int _bgHeight = 0;
private int _numChoices = 0;
private boolean _hasFocus = false;
private static final int HIGHLIGHT_COLOR = 0xFF185AB5; // blue-ish
private static final int RADIUS = 1; // rounded corner radius in pixels
private static final int DFLT_PADDING = 20;
public CustomChoiceField(Object[] choices, int initialIndex) {
super("", choices, initialIndex);
_numChoices = choices.length;
}
public int getPreferredHeight() {
return _bgHeight;
}
public int getPreferredWidth() {
return _bgWidth;
}
protected void layout(int width, int height) {
if (_bgWidth == 0 || _bgHeight == 0) {
if (height <= Display.getHeight()) {
// probably using custom Manager to specify size
_bgWidth = width;
_bgHeight = height;
} else {
// use default sizing
_bgHeight = DFLT_PADDING + getHeightOfChoices();
for (int i = 0; i < _numChoices; i++) {
_bgWidth = Math.max(_bgWidth, DFLT_PADDING + getWidthOfChoice(i));
}
}
}
super.layout(_bgWidth, _bgHeight);
super.setExtent(_bgWidth, _bgHeight);
}
protected void applyTheme(Graphics arg0, boolean arg1) {
// do nothing
}
protected void drawFocus(Graphics g, boolean on) {
// do nothing .. handled manually in paint(g)
}
protected void onFocus(int direction) {
_hasFocus = true;
super.onFocus(direction);
invalidate();
}
protected void onUnfocus() {
_hasFocus = false;
super.onUnfocus();
invalidate(); // required to clear focus
}
protected void paint(Graphics g) {
int oldColor = g.getColor();
// field color depends on whether we have focus or not
int bgColor = (_hasFocus) ? HIGHLIGHT_COLOR : Color.BLACK;
// when the field has focus, we make it a little less transparent
int alpha = (_hasFocus) ? 0xDD : 0xBB;
g.setColor(bgColor);
g.setGlobalAlpha(alpha);
g.fillRoundRect(0, 0, _bgWidth, _bgHeight, RADIUS, RADIUS);
// draw a plain white line as a border
g.setColor(Color.WHITE);
g.setGlobalAlpha(0xFF);
g.drawRoundRect(0, 0, _bgWidth, _bgHeight, RADIUS, RADIUS);
// draw the currently selected choice's text (also in white)
String text = (String)getChoice(getSelectedIndex());
int y = (_bgHeight - getFont().getHeight()) / 2;
g.drawText(text, 0, y, DrawStyle.HCENTER | DrawStyle.TOP, _bgWidth);
g.setColor(oldColor);
}
}
And you use the CustomChoiceField like this:
private ObjectChoiceField[] ocf = new ObjectChoiceField[3];
public ObjectChoiceScreen() {
super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR);
Object[] choices1 = new Object[] { "one", "two", "three" };
ocf[0] = new CustomChoiceField(choices1, 0);
Object[] choices2 = new Object[] { "ichi", "ni", "san" };
ocf[1] = new CustomChoiceField(choices2, 0);
Object[] choices3 = new Object[] { "uno", "dos", "tres" };
ocf[2] = new CustomChoiceField(choices3, 0);
for (int i = 0; i < ocf.length; i++) {
ocf[i].setMargin(new XYEdges(10, 10, 10, 10));
}
getMainManager().addAll(ocf);
This isn't production code, so you'll need to test it yourself. For example, it doesn't handle changing the choices with setChoices(). But, it's a start, and will get you something like this:
You'll notice the difference in color between the first two object choice fields, and the bottom one, which is focused.
My code has the same popup for selecting choices as the normal ObjectChoiceField. So, you still may get rounded corners that way. In my case, I didn't need to change that look and feel, so I'm not sure how you might change that, too.

Image gone After Focusing

This is before focus state. It work fine.
This is on focusing state. It work fine.
This is after focus state. It occurred problem where the image gone.
It works fine for the top right but top left image got problem.
Here is my custom VerticalFieldManager:
public class Custom_TopField extends HorizontalFieldManager implements
FieldChangeListener {
private Bitmap bg = Bitmap.getBitmapResource("header_bar.png");
private Bitmap download = Bitmap.getBitmapResource("btn_download.png");
private Bitmap downloadactive = Bitmap
.getBitmapResource("btn_download_active.png");
private Bitmap refresh = Bitmap.getBitmapResource("icon_refresh.png");
private Bitmap refreshactive = Bitmap
.getBitmapResource("icon_refresh_active.png");
private Bitmap back = Bitmap.getBitmapResource("btn_back.png");
private Bitmap backctive = Bitmap.getBitmapResource("btn_back_active.png");
private Bitmap news = Bitmap.getBitmapResource("icon_news.png");
private Bitmap newsactive = Bitmap
.getBitmapResource("icon_news_active.png");
private Custom_ButtonField downloadbtn, refreshbtn, backbtn, newsbtn;
private Custom_LabelField title;
Custom_TopField(final MainScreen mainscreen) {
Background background = BackgroundFactory.createBitmapBackground(bg);
setBackground(background);
title = new Custom_LabelField("东方日报", DrawStyle.ELLIPSIS
| LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER
| Field.FOCUSABLE, Color.WHITE) {
protected boolean navigationClick(int status, int time) {
Main.getUiApplication().pushScreen(new Main_AllLatestNews());
Main.getUiApplication().popScreen(mainscreen);
return true;
}
};
title.setFont(Font.getDefault().derive(Font.BOLD, 33));
add(title);
downloadbtn = new Custom_ButtonField(download, downloadactive,
downloadactive);
downloadbtn.setChangeListener(this);
add(downloadbtn);
refreshbtn = new Custom_ButtonField(refresh, refreshactive,
refreshactive);
refreshbtn.setChangeListener(this);
add(refreshbtn);
backbtn = new Custom_ButtonField(back, backctive, backctive);
backbtn.setChangeListener(this);
add(backbtn);
/*newsbtn = new Custom_ButtonField(news, newsactive, newsactive);
newsbtn.setChangeListener(this);
add(newsbtn);*/
}
protected void sublayout(int width, int height) {
Field field = getField(0);
layoutChild(field, 120, Font.getDefault().getHeight());
setPositionChild(field, (getPreferredWidth() - title.getWidth()) / 2,
15);
field = getField(1);
layoutChild(field, download.getWidth(), download.getHeight());
setPositionChild(field, getPreferredWidth()
- (download.getWidth() + 10),
getPreferredHeight() - (download.getHeight() + 5));
field = getField(2);
layoutChild(field, refresh.getWidth(), refresh.getHeight());
setPositionChild(field,
getPreferredWidth() - (refresh.getWidth() + 10),
getPreferredHeight() - (refresh.getHeight() + 5));
field = getField(3);
layoutChild(field, back.getWidth(), back.getHeight());
setPositionChild(field, 10, 5);
/*field = getField(4);
layoutChild(field, news.getWidth(), news.getHeight());
setPositionChild(field, 10, 5);*/
width = Math.min(width, getPreferredWidth());
height = Math.min(height, getPreferredHeight());
setExtent(width, height);
}
public int getPreferredHeight() {
return 70;
}
public int getPreferredWidth() {
return Display.getWidth();
}
public void paint(Graphics graphics) {
int rectHeight = getPreferredHeight();
int rectWidth = getPreferredWidth();
graphics.drawRect(0, 0, rectWidth, rectHeight);
super.paint(graphics);
}
public void fieldChanged(Field field, int context) {
if (field == downloadbtn) {
} else if (field == refreshbtn) {
} else if (field == backbtn) {
} else if (field == newsbtn) {
}
}
}
Here is custom button field
public class Custom_ButtonField extends ButtonField {
Bitmap mNormal;
Bitmap mFocused;
Bitmap mActive;
int mWidth;
int mHeight;
private int color = -1;
String text;
public Custom_ButtonField(Bitmap normal, Bitmap focused, Bitmap active) {
super(CONSUME_CLICK | Field.FOCUSABLE);
mNormal = normal;
mFocused = focused;
mActive = active;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE,
BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
}
public Custom_ButtonField(String text, Bitmap normal, Bitmap focused,
Bitmap active, int color) {
super(CONSUME_CLICK | Field.FOCUSABLE);
this.color = color;
mNormal = normal;
mFocused = focused;
mActive = active;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE,
BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
this.text = text;
}
protected void onFocus(int direction) {
super.onFocus(direction);
}
protected void onUnfocus() {
super.onUnfocus();
}
protected void paint(Graphics graphics) {
Bitmap bitmap = null;
switch (getVisualState()) {
case VISUAL_STATE_NORMAL:
bitmap = mNormal;
break;
case VISUAL_STATE_FOCUS:
bitmap = mFocused;
break;
case VISUAL_STATE_ACTIVE:
bitmap = mActive;
break;
default:
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 25));
graphics.setColor(color);
graphics.drawText(text, (mNormal.getWidth() - Font.getDefault()
.getAdvance(text)) / 2, ((mNormal.getHeight() - Font
.getDefault().getHeight()) / 2) + 10, DrawStyle.HCENTER
| DrawStyle.VCENTER);
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
}
This is the second problem just like this I've seen in the last couple weeks.
Background
To understand the solution, first you should understand the basic UI classes in BlackBerry.
First, we have the Field class. A Field is the base class of the normal UI components. If you write a UI component yourself, from scratch, then you would subclass Field:
public class MyWidget extends Field {
However, if there already exists a BlackBerry class that does almost what you need, and you just need to change its behaviour a bit, then you would subclass something else. For example:
public class MyButtonWidget extends ButtonField {
The same pattern exists for the Manager class. If you are writing a Manager from scratch, then extend Manager:
public class MyManager extends Manager {
which involves doing this, according to the BlackBerry docs:
Implementing your own layout manager
If you have particular needs, you
can implement your own manager. Extend the Manager class, and
implement sublayout, getPreferredWidth, and getPreferredHeight. For
efficiency, you may optionally override subpaint.
However, if an existing Manager subclass already does most of what you need, and you just want to customize it, then you might consider extending that subclass:
public class MyHorizontalManager extends HorizontalFieldManager {
In your case, your Custom_TopField is doing all of the required work for a fully custom Manager (see the highlighted quote above from the javadocs). So, there's not really any reason for you to extend HorizontalFieldManager. A HorizontalFieldManager is used when you just want to add() your fields, and have them all laid out horizontally. But, you do that explicitly in your sublayout() code. As it turns out, it looks like your logic is competing with the base class.
Solution
So, what you should do, is have your class just extend Manager:
public class Custom_TopField extends Manager implements FieldChangeListener {
If you do that, you will need to call a different super constructor. Something like this (you might want to pick different style constants depending on your needs):
Custom_TopField(final MainScreen mainscreen) {
super(Manager.USE_ALL_WIDTH | Manager.NO_VERTICAL_SCROLL | Manager.NO_HORIZONTAL_SCROLL);
Another alternative would be to simply not implement sublayout(), extend HorizontalFieldManager like you originally had, and then control layout with the child fields' margins and long style flags. But, since the solution I gave above requires only changing 2 lines of code, that's probably the easiest for you this time.
Other Problem(s)
I also noticed in your code, and screenshots, that the Download button doesn't show up. I don't know the exact size of all your png images, but if the refresh and download images are the same size, then your current logic is just laying out the refresh button right over the download button. So, the download button is hidden. That's probably not what you want?

Custom BitmapField bug on unfocus and scroll (BlackBerry)

I have been having this annoying problem when trying to implement a picture gallery on BlackBerry 6.
Everything works, however when the focus changes from the top buttons to say the pictures further down the screen, the images seem to glitch and not paint themselves correctly. Please see the images below for an example:
(Focus is on the top of the screen(not shown))
(Focus is now on the bottom left image, note that the top image is now blank for an unknown reason)
And this happens no matter how many pictures I add to the tumbnail gallery.
Now here is my code, (a part of it concerning the drawing of the thumbnails)
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
try{
Storage.loadPicture();
}catch(NullPointerException e){
e.printStackTrace();
}
this.setTitle(new LabelField(_resources.getString(PRODUCT_IMAGE), Field.FIELD_HCENTER));
if(ToolbarManager.isToolbarSupported())
{
Toolbar tb = new Toolbar();
setToolbar(tb.createToolBar());
}
else{
Toolbar tb = new Toolbar();
add(tb.createNavBar());
}
picVector = Storage.getPicture(currentProduct);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
vfMain = new VerticalFieldManager();
vfMain.add(logo);
vfMain.add(new SeparatorField());
add(vfMain);
prepareBmpFields();
}
private void prepareBmpFields() {
System.out.println("This is the vector size: " + picVector.getPicVector().size());
LayoutManager manager = new LayoutManager();
FieldChangeListener itemListener = new ButtonListener();
mBmpFields = new ImageButtonField[picVector.getPicVector().size()];
for (int i = 0; i < picVector.getPicVector().size(); i++) {
/*EncodedImage image = EncodedImage
.getEncodedImageResource((String)imageVector.elementAt(i));*/
byte[] data = getData((String)picVector.getPicVector().elementAt(i));
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
eImage = ImageResizer.resizeImage(eImage, mImgWidth, mImgHeight);
ImageButtonField currentImage = new ImageButtonField(eImage.getBitmap());
currentImage.setAssociatedPath((String)picVector.getPicVector().elementAt(i));
mBmpFields[i] = currentImage;
mBmpFields[i].setChangeListener(itemListener);
manager.add(mBmpFields[i]);
}
vfMain.add(manager);
}
private class LayoutManager extends VerticalFieldManager {
public LayoutManager() {
super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
}
protected void sublayout(int width, int height) {
int columns = mScrWidth / (mImgWidth + 2 * mImgMargin);
int scrWidth = Display.getWidth();
int rows = mBmpFields.length / columns
+ (mBmpFields.length % columns > 0 ? 1 : 0);
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int posX = j * (mImgWidth + 2 * mImgMargin) + mImgMargin;
int posY = i * (mImgHeight + 2 * mImgMargin) + mImgMargin;
if(mBmpFields.length > counter){
Field field = mBmpFields[counter];
layoutChild(field, mImgWidth, mImgHeight);
setPositionChild(field, posX, posY);
counter++;
};
}
}
if(Display.getWidth() < Display.getHeight()){
setExtent(mScrWidth, (int)(mScrHeight*1.25));
}
else{
setExtent(mScrWidth, (int)(mScrHeight*2));
}
}
public int getPreferredWidth() {
return mScrWidth;
}
public int getPreferredHeight() {
return mScrHeight;
}
}
}
I have removed many non relevant parts of the code, but the needed code is there.
Does anyone know what could be causing this problem? Thanks for your help!
Edit: as requested, here is my implementation of ImageButtonField class:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;
public class ImageButtonField extends BitmapField{
String associatedPath ="";
BitmapField image2;
public ImageButtonField(Bitmap image) {
super(image);
}
public void setAssociatedPath(String path){
associatedPath = path;
}
public String getAssociatedPath(){
return associatedPath;
}
public boolean isFocusable() {
return true;
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
protected void drawFocus(Graphics graphics, boolean on) {
}
protected void onFocus(int direction) {
// only change appearance if this button is enabled (aka editable)
if (isEditable()) {
invalidate(); // repaint
}
super.onFocus(direction);
}
public void onUnfocus() {
invalidate(); // repaint
super.onUnfocus();
}
protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}
protected boolean trackwheelClick(int status, int time) {
fieldChangeNotify(0);
return true;
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (isFocus()) {
graphics.setGlobalAlpha(128);
graphics.setColor(0x888888);
graphics.fillRect(0, 0, getWidth(), getHeight());
}else{
graphics.setGlobalAlpha(0);
graphics.setColor(0x000000);
graphics.fillRect(0, 0, getWidth(), getHeight());
//graphics.drawBitmap(0, 0, getWidth(), getHeight(), image2.getB, 0, 0);
}
}
protected boolean keyChar(char character, int status, int time) {
if(Characters.ENTER == character || Characters.SPACE == character) {
fieldChangeNotify(0);
return true;
}
return super.keyChar(character, status, time);
}
}
Ok, so you can disregard my first answer, but since I didn't have your ImageButtonField code at the time, I don't want to throw it out ... maybe someone else will find it useful.
In the end, I didn't need to make any changes to ImageButtonField, but I did change your LayoutManager class. The way I figured out that it was the problem was I just started replacing your custom UI classes with built-in ones. I replaced ImageButtonField with BitmapField. That didn't fix it. Then, I replaced LayoutManager with FlowFieldManager and that fixed it. So, I knew where the problem was.
My solution:
private class LayoutManager extends Manager {
public LayoutManager() {
super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
}
protected void sublayout(int width, int height) {
setExtent(width, height);
// TODO: maybe always set the same virtual extent?
if (Display.getWidth() < Display.getHeight()) {
setVirtualExtent(mScrWidth, (int) (mScrHeight * 1.25));
} else {
setVirtualExtent(mScrWidth, (int) (mScrHeight * 2));
}
int columns = mScrWidth / (mImgWidth + 2 * mImgMargin);
// int scrWidth = Display.getWidth();
int rows = mBmpFields.length / columns + (mBmpFields.length % columns > 0 ? 1 : 0);
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int posX = j * (mImgWidth + 2 * mImgMargin) + mImgMargin;
int posY = i * (mImgHeight + 2 * mImgMargin) + mImgMargin;
if (mBmpFields.length > counter) {
Field field = mBmpFields[counter];
layoutChild(field, mImgWidth, mImgHeight);
setPositionChild(field, posX, posY);
counter++;
}
}
}
}
public int getPreferredWidth() {
return mScrWidth;
}
public int getPreferredHeight() {
return mScrHeight;
}
}
I can't say for sure that I understand why your original code wasn't working, but I can say that I wouldn't have done a few of the things in the original code:
The original code was extending VerticalFieldManager but was doing all the work itself, in sublayout(). So, I don't think there was any point extending VerticalFieldManager. I changed it to just extend Manager.
The original code was calling setExtent() with different sizes. I don't think that's what you wanted. Extent is the actual size of the Field. Virtual extent is the virtual size, which is what you want to set larger than the actual extent, in order to enable scrolling. You don't need to dynamically calculate different extents for portrait vs. landscape because the width and height parameters passed to sublayout() will already reflect that. I'm not sure you really even need to be setting different virtual extents either. I think you should probably always set the virtual extent height to the number of rows times picture height, accounting for margins.
You had an unused variable scrWidth in your original code. I commented it out above.
You also posted this question recently, right? Am I correct in assuming that the ImageButtonField you refer to here is the same one you were working on in the other question?
I can't see your full implementation of ImageButtonField, which you should probably post here, too. However, looking at the answers to your other question, I have a feeling that you're doing some custom focus handling in ImageButtonField, and maybe it's not being done quite right. In any case, that class may be where the problem is.
I have a similar Field subclass of my own, and here are the focus handling methods I define:
public class CustomButtonField extends Field {
private Bitmap _button; // the currently displayed button image
private Bitmap _on; // image for 'on' state (aka in-focus)
private Bitmap _off; // image for 'off' state (aka out-of-focus)
protected void onFocus(int direction) {
// only change appearance if this button is enabled (aka editable)
if (isEditable()) {
_button = _on;
invalidate(); // repaint
}
super.onFocus(direction);
}
protected void onUnfocus() {
_button = _off;
invalidate(); // repaint
super.onUnfocus();
}
protected void drawFocus(Graphics graphics, boolean on) {
// override superclass implementation and do nothing
}
public boolean isFocusable() {
return true;
}
I also have a custom implementation of paint(). I won't show it all here, because a lot of the code probably has nothing to do with your problem, but my paint() does include this call:
graphics.drawBitmap(_padding, _padding, _fieldWidth, _fieldHeight, _button, 0, 0);
You might not care about the fact that I have separate images for focused, and unfocused states ... maybe you show the same image at all times.
But, probably the thing to check is your onFocus() and onUnfocus() methods. You may need to add a call to invalidate() as I have.
Looking at Rupak's answer to your other question, it would also be good to check your ImageButtonField.paint() method, and make sure you aren't neglecting to do important drawing steps if the field is not in focus.

Vertical scrollbar with jump points - setVerticalScroll locking UI

I have a question about the BlackBerry VerticalScrollField and scrolling which seems to lock or make the UI unstable. The following code is a BlackBerry screen with worlds as content on the left (in a scroll field) and a jumpbar off to the right that allows clicking into the content.
When a jump letter is clicked the setVerticalScroll method is called, it performs the scroll but has the unfortunate side effect of rendering the UI unstable or unusable. The scroll call is done on the UI thread so its not clear what the source of the error is. The app is being tested in a 6.0 simulator.
I've included the class which can be copied into BB Eclipse for hacking/testing.
The section that kicks of the scrolling can be found towards the bottom with the following code:
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
scroller.setVerticalScroll(y, true);
}});
Here's the full class:
package test;
import java.util.Vector;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class Startup extends UiApplication {
private int[] jump;
static final String[] words = new String[]{
"auto", "apple", "bear", "car", "farm", "ferret", "gold",
"green", "garden", "hedge", "happy", "igloo", "infrared",
"jelly", "kangaroo", "lemon", "lion", "marble", "moon",
"nine", "opera", "orange", "people", "puppy", "pear",
"quince", "race", "run", "sunset", "token", "willow", "zebra"
};
private final static String[] alphabet = new String[]{"A","B","C","D","E",
"F","G","H","I","J","K","L","M","N","O","P","Q","R",
"S","T","U","V","W","X","Y","Z","#"};
private VerticalFieldManager scroller;
public Startup() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().pushScreen(new ScrollScreen());
}
});
}
public static void main(String[] args) {
ApplicationManager app = ApplicationManager.getApplicationManager();
while (app.inStartup()) {
try { Thread.sleep(200); } catch (Throwable e) {}
}
Startup startup = new Startup();
startup.enterEventDispatcher();
}
/**
* Screen with content in a scrollbar left and a letters on the right that
* can be used to jump into the content.
*/
class ScrollScreen extends MainScreen {
public ScrollScreen() {
super(NO_HORIZONTAL_SCROLL | NO_VERTICAL_SCROLL);
HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_HEIGHT | NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL){
protected void sublayout(int maxWidth, int maxHeight) {
Field scroll = getField(0);
Field alpha = getField(1);
layoutChild(alpha, maxWidth, maxHeight);
layoutChild(scroll, maxWidth-alpha.getWidth(), maxHeight);
setPositionChild(scroll, 0, 0);
setPositionChild(alpha, maxWidth-alpha.getWidth(), 0);
setExtent(maxWidth, maxHeight);
}
};
hfm.add(createScrollContent());
hfm.add(createAlphabetJumpBar());
add(hfm);
}
private Field createScrollContent() {
Vector vocabulary = new Vector();
for (int ii=0; ii<alphabet.length; ii++)
vocabulary.addElement(alphabet[ii]);
scroller = new VerticalFieldManager(VERTICAL_SCROLL | USE_ALL_WIDTH) {
protected void sublayout(int maxWidth, int maxHeight) {
// Record the jump offsets
int y = 0;
for (int ii=0; ii<getFieldCount(); ii++) {
Field field = getField(ii);
layoutChild(field, maxWidth, maxHeight);
setPositionChild(field, 0, y);
if (field instanceof WordField) {
WordField object = (WordField)field;;
char character = object.getWord().toLowerCase().charAt(0);
int offset = ((int)character)-(int)alphabet[0].toLowerCase().charAt(0);
if (offset < 0 || offset > jump.length)
offset = jump.length-1;
while (offset >= 0 && offset < jump.length && jump[offset] == 0) {
jump[offset] = y;
offset--;
}
}
y += field.getHeight();
}
int offset = jump.length-1;
do {
jump[offset] = y;
offset--;
} while (offset >= 0 && jump[offset] == 0);
setExtent(maxWidth, maxHeight);
setVirtualExtent(maxWidth, y+10);
}
};
jump = new int[alphabet.length];
Font largeFont = Font.getDefault().derive(Font.PLAIN, 46);
for (int ii=0; ii<words.length; ii++) {
WordField wordField = new WordField(words[ii]);
wordField.setFont(largeFont);
scroller.add(wordField);
}
return scroller;
}
private Field createAlphabetJumpBar() {
VerticalFieldManager vfm = new VerticalFieldManager() {
protected void sublayout(int maxWidth, int maxHeight) {
int y = 0;
int width = 0;
double allowedAlphaHeight = (double)maxHeight / (double)getFieldCount();
for (int ii=0; ii<getFieldCount(); ii++) {
WordField field = (WordField)getField(ii);
layoutChild(field, maxWidth, (int)allowedAlphaHeight);
setPositionChild(field, 0, y);
y += field.getHeight();
double paddedY = Math.floor(allowedAlphaHeight*(ii+1));
if (y < paddedY) y = (int)paddedY;
width = Math.max(width, field.getWidth());
}
setExtent(width, maxHeight);
}
};
for (int ii=0; ii<alphabet.length; ii++) {
vfm.add(new AlphaField(alphabet[ii]){
protected boolean touchEvent(TouchEvent message) {
if (message.getEvent() == TouchEvent.UP) {
int startOffset = (int)alphabet[0].charAt(0);
int offset = ((int)getWord().charAt(0)) - startOffset;
final int y = offset == 0 ? 0 : jump[offset - 1];
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
scroller.setVerticalScroll(y, true);
}});
}
return true;
}
});
}
return vfm;
}
class WordField extends LabelField {
private final String word;
public WordField(String word) {
super(word);
this.word = word;
}
public String getWord() { return word; }
}
Font alphaFont = null;
class AlphaField extends WordField {
public AlphaField(String word) {
super(word);
}
protected void layout(int width, int height) {
if (alphaFont == null)
alphaFont = Font.getDefault().derive(Font.PLAIN, height);
setExtent(alphaFont.getAdvance(getWord()), alphaFont.getHeight());
}
protected void paint(Graphics graphics) {
graphics.setFont(alphaFont);
graphics.drawText(getWord(), 0, 0);
}
}
/**
* For debugging.
* #see net.rim.device.api.ui.Screen#keyChar(char, int, int)
*/
protected boolean keyChar(char c, int status, int time) {
if ('o' == c) { // shows the jump offsets into the scroll field
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
StringBuffer buf = new StringBuffer();
for (int ii=0; ii<jump.length; ii++) {
buf.append(alphabet[ii]+"="+jump[ii]);
if (ii<jump.length-1)
buf.append(",");
}
Status.show("offsets="+buf.toString());
}});
}
return super.keyChar(c, status, time);
}
}
}
You're using UiApplication.invokeLater in a few places where you're already on the UI event thread, so those are redundant - the debug code in keyChar and the setVerticalScroll call from the touchEvent handler. The Runnable is executed synchronously when you do an invokeLater from the UI thread, with no delay specified.
Are you sure you want to set the scroll explicitly? One option would be to set the focus on the WordField you are interested in, by calling setFocus(), then the OS will do the scrolling events to move that field on screen for you.
If you really need to explicitly set the vertical scroll, your problem may be that the touch event is already causing scroll, so setting it again causes problems. You can get around this by specifying a one millisecond delay for your invokeLater(...). This means your Runnable will be added to the event queue, instead of executing synchronously. That way the scroll won't be changed in the middle of another event call-stack.
Finally tracked down the issue - if the touchEvent for the alphabet label field returns a true then it locks up the main scroll field, if however return super.touchEvent(message) is called the scrolling happens and the scroll field can still be scrolled up and down by clicking on the screen.
This may be a bug in the BlackBerry OS or just the simulator. The Field.touchEvent() documentation for 6.0 recommends returning true if the method consumes the event; however doing so (at least in the above code) causes another UI field to loose the ability to detect touch events which would cause it to scroll.

accessing Inner class while creating BitmapField & adding it in HorizontalFieldManager

I'm creating a inner class in a method. After that I am accessing some statements like,
public class Test extends MainScreen
{
HorizontalFieldManager hfm;
Bitmap bitmap[] = new Bitmap[100];
BitmapField[] bitmapField = new BitmapField[100];
int countBitmap = 0;
Test()
{
VerticalFieldManager vfm_Main = new VerticalFieldManager();
hfm = new HorizontalFieldManager(HorizontalFieldManager.USE_ALL_WIDTH);
vfm_Main.add(hfm);
add(vfm_Main);
}
void drawBitmap()
{
bitmap[countBitmap] = new Bitmap(100, 100);
bitmapField[countBitmap] = new BitmapField(bitmap[countBitmap]){
public void paint(Graphics g)
{
................
................
g.drawLine(x1,y1,x2,y2);
}
}
synchronized(UiApplication.getEventLock())
{
for(int i = 0 ; i < bitmapField.length; i++)
{
if(bitmapField[i] != null)
{
bitmapField[i].setBitmap(bitmap[i]);
}
}
hfm.add(bitmapField[countBitmap]);
countBitmap++;
But here the problem is after creating the bitmap & before creating the bitmapField, control goes to
synchronized(UiApplication.getEventLock()){hfm.add(bitmapField[countBitmap]); }
So before creating the bitmapField, it adds it in hfm.
So the output is coming like "Everytime a new BitmapField is added in hfm (means at the same position by replacing the previous one)". But I want the BitmapFields come next to each other in hfm.
How to do it?
Any solution why the control goes first to hfm.add() before the new bitmapField() inner class?
first of all, several suggestions about code:
see no reason using synchronized since it's UI thread
don't setBitmap, bitmap is already passed to BitmapField constructor
actually all BitmapFields come next to each other in hfm, to make it clear, I've add number to each one.
if you want some custom constructor or new fields in BitmapField, it's better to create new class as an extension of BitmapField
class TestScr extends MainScreen {
HorizontalFieldManager hfm;
Bitmap bitmap[] = new Bitmap[100];
BitmapField[] bitmapField = new BitmapField[100];
TestScr() {
hfm = new HorizontalFieldManager();
add(hfm);
drawBitmap();
}
void drawBitmap() {
for (int i = 0; i < 5; i++) {
bitmap[i] = new Bitmap(50, 50);
Graphics graphics = new Graphics(bitmap[i]);
graphics.setColor(Color.RED);
String number = Integer.toString(i);
Font font = graphics.getFont().derive(Font.BOLD, 40, Ui.UNITS_px);
graphics.setFont(font);
int textWidth = graphics.getFont().getAdvance(number);
int textHeight = graphics.getFont().getHeight();
int x = (bitmap[i].getWidth() - textWidth) / 2;
int y = (bitmap[i].getHeight() - textHeight) / 2;
graphics.drawText(number, x, y);
bitmapField[i] = new BitmapField(bitmap[i]) {
public void paint(Graphics g) {
super.paint(g);
int width = getWidth() - 1;
int height = getHeight() - 1;
g.setColor(Color.GREEN);
g.drawLine(0, 0, width, 0);
g.drawLine(width, 0, width, height);
g.drawLine(width, height, 0, height);
g.drawLine(0, height, 0, 0);
}
};
hfm.add(bitmapField[i]);
}
}
}

Resources