Blackberry video with text display prob - blackberry

I need a video screen and under the video play, I want to show two lines of text like below.
For that I am using following code.
public final class PlayVideoScreen extends MainScreen {
private Player player;
private VideoControl videoControl;
public PlayVideoScreen() {
// ms.setTitle(new LabelField("Let's play some video..."));
LabelField lf = new LabelField("Video Play");
try {
// Create a new Player pointing to the video file.
// This can use any valid URL.
player = javax.microedition.media.Manager
.createPlayer("file:///SDCard/BlackBerry/videos/sample.avi");
player.realize();
// Create a new VideoControl.
videoControl = (VideoControl) player.getControl("VideoControl");
// Initialize the video mode using a Field.
Field videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
add(videoField);
VolumeControl volume = (VolumeControl) player
.getControl("VolumeControl");
volume.setLevel(30);
player.start();
// Set the video control to be visible.
// videoControl.setVisible(true);
} catch (MediaException me) {
Dialog.alert(me.toString());
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
add(lf);
LabelField lf2 = new LabelField("How r you?");
add(lf2);
}
public boolean onClose() {
// Clean up the player resources.
player.close();
videoControl.setVisible(false);
close();
return true;
}
}
Now what is may be the height of video, the view is taking scroll and the text is only visible after scrolling. I am using a device of screen size 320X240px. I have even test with a video of 320X150px. But the text is not visible without scrolling, although there is lots of free space above and bottom of the video. What is problem in my code? How to solve it?

There are several ways to solve your issue. The easiest in your case is to use the MainScreen#setStatus which sets the contents of this screen's status section.
Instead of adding the LabelFields directly, add them in the following way:
VerticalFieldManager vfm = new VerticalFieldManager();
vfm.add(lf);
vfm.add(lf2);
setStatus(vfm);
EDIT: An alternative solution would be to layout and positions the child field by yourself. In order to do so, you can override sublayout() of the PlayVideoScreen or introduce another manager (VerticalFieldManager), add all fields (video and labels) to it and override its sublayout() method.
Below is your code with the aforementioned modifications
public PlayVideoScreen() {
super(NO_VERTICAL_SCROLL);
// ms.setTitle(new LabelField("Let's play some video..."));
final LabelField lf = new LabelField("Video Play");
try {
// Create a new Player pointing to the video file.
// This can use any valid URL.
player = javax.microedition.media.Manager
.createPlayer("file:///SDCard/BlackBerry/videos/sample.avi");
player.realize();
// Create a new VideoControl.
videoControl = (VideoControl) player.getControl("VideoControl");
// Initialize the video mode using a Field.
final Field videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
VolumeControl volume = (VolumeControl) player
.getControl("VolumeControl");
volume.setLevel(30);
player.start();
// Set the video control to be visible.
// videoControl.setVisible(true);
final LabelField lf2 = new LabelField("How r you?");
VerticalFieldManager vfm = new VerticalFieldManager(NO_VERTICAL_SCROLL) {
protected void sublayout(int maxWidth, int maxHeight) {
int heightLeft = maxHeight;
// layout the children fields
layoutChild(lf, maxWidth, heightLeft);
heightLeft -= lf.getHeight();
layoutChild(lf2, maxWidth, heightLeft);
heightLeft -= lf2.getHeight();
layoutChild(videoField, maxWidth, heightLeft);
// position the children fields
int yPos = 0;
setPositionChild(videoField, 0, yPos);
yPos += videoField.getHeight();
setPositionChild(lf, 0, yPos);
yPos += lf.getHeight();
setPositionChild(lf2, 0, yPos);
setExtent(maxWidth, maxHeight);
};
};
vfm.add(videoField);
vfm.add(lf);
vfm.add(lf2);
add(vfm);
} catch (MediaException me) {
Dialog.alert(me.toString());
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
}

Related

Change Image resolution in Android with OpenCV

I am capturing frames using JavaCameraView and OpencCV, but i am stuck at default 620*480 resolution, which is not my requirement my phone can support 1280*720 resolution, I have been trying to find the solution for many days, tried many options but could not alter default image/frame resolution.
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("OpenCv", "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d("OpenCv", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, mLoaderCallback);
} else {
Log.d("OpenCv", "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);
mOpenCvCameraView.setMaxFrameSize(720,1280);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#Override
public void onCameraViewStarted(int width, int height) {
// Recieve Image Data when the caera preview starts
mRgba = new Mat(height, width, CvType.CV_8UC4);
mRgbaT = new Mat(height, width, CvType.CV_8UC4);
mRgbaF = new Mat(height, width, CvType.CV_8UC4);
//End
mSpectrum = new Mat();
mBlobColorRgba = new Scalar(255);
mBlobColorHsv = new Scalar(255);
SPECTRUM_SIZE = new Size(400, 400);
CONTOUR_COLOR = new Scalar(255,0,0,255);
}
#Override
public void onCameraViewStopped() {
mRgba.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
timeofFrame = System.currentTimeMillis();
mRgba = inputFrame.rgba();
Core.transpose(mRgba,mRgbaT);
//Rotate 90 degrees//
Imgproc.resize(mRgbaT,mRgbaF,mRgbaF.size(),0,0,0);
Core.flip(mRgbaF,mRgba,1);
return mRgba;
}
}
If your JavaCameraView is presented in landscape you can try replace your
mOpenCvCameraView.setMaxFrameSize(720,1280);
to
mOpenCvCameraView.setMaxFrameSize(1280,720);
If not, try to change orientation of your activity class in manifest.xml like
<activity android:name="CameraActivity"
android:screenOrientation="landscape" />
after that change MaxFrameSize:
mOpenCvCameraView.setMaxFrameSize(1280,720);
Open JavaCameraView.java, then manually set the width and height inside InitializeCamera():
...
/* Now set camera parameters */
try {
Camera.Parameters params = mCamera.getParameters();
Log.d(TAG, "getSupportedPreviewSizes()");
List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();
if (sizes != null) {
/* Select the size that fits surface considering maximum size allowed */
width = 1080;
height = 1920;
Size frameSize = calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height);
...
In my case, it's portrait. So switch it up if you want landscape. Unfortunately this is hardcoding, so please someone chime in for a dynamic solution.

Blackberry screen does not scroll back all the way

I have an app which is displaying a news screen with app banner and title + image + details (RichTextField) and an Ad banner on the bottom of the screen so once I scroll down to read the details I can't get back to the top .. it stops on the middle of the screen as you see in these pictures ..I don't know why .. it works perfectly when you use the touch on touch screen devices
here's my code for this screen ... please help
public class DetailsScreen_en extends MainScreen {
AppManager appManager;
private Detailsbean_en bean;
private AppManager manager;
private BitmapField bitmapField;
private LabelField titleField;
private LabelField dateField;
private RichTextField articleField;
private Bitmap bitmap;
private BitmapField bar;
private HorizontalFieldManager hfm;
Adsbean[] adsBean;
BitmapField ad;
VerticalFieldManager otherStuff;
VerticalFieldManager vvv;
Timer time;
TimerTask task;
private HorizontalFieldManager admanager;
private int adCounter = 0;
private boolean status;
private int tour;
public DetailsScreen_en(boolean status, int tour) {
appManager = AppManager.getInstance();
adsBean = appManager.getAdsBean();
Locale.setDefault(Locale.get(Locale.LOCALE_en));
// ScreenOne.showLoadingScreen();
this.status = status;
this.tour = tour;
XYEdges padding = new XYEdges(10, 10, 10, 10);
HTMLParser parser = new HTMLParser();
vvv = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL
| Field.FOCUSABLE) {
protected void sublayout(int maxWidth, int maxHeight) {
// TODO Auto-generated method stub
super.sublayout(maxWidth, maxHeight);
setExtent(maxWidth, Display.getHeight() - ad.getHeight());
}
};
hfm = new HorizontalFieldManager();
bar = new BitmapField(DesignSizes.FanClubBar(), Field.FIELD_HCENTER
| Field.NON_FOCUSABLE | Field.READONLY);
hfm.add(bar);
vvv.add(hfm);
hfm = new HorizontalFieldManager();
manager = AppManager.getInstance();
bean = manager.getBean_en();
// System.out.println("DATE: "+ bean.getNewsDate() );
// another try ...
Date _date;
Calendar _cal = Calendar.getInstance();
_cal.set(Calendar.YEAR,
Integer.parseInt(bean.getNewsDate().substring(0, 4)));
_cal.set(Calendar.MONTH,
Integer.parseInt(bean.getNewsDate().substring(5, 7)) - 1);
_cal.set(Calendar.DAY_OF_MONTH,
Integer.parseInt(bean.getNewsDate().substring(8, 10)));
_date = _cal.getTime();
DateFormat dff = new SimpleDateFormat("dd MMMM yyyy");
String datedatedate = dff.formatLocal(_date.getTime());
dateField = new LabelField(datedatedate);
dateField.setPadding(padding);
titleField = new LabelField(bean.getNewsTitle(), Field.FIELD_LEFT) {
protected void paint(Graphics graphics) {
// TODO Auto-generated method stub
graphics.setColor(Color.ORANGE);
super.paint(graphics);
}
};
titleField.setPadding(padding);
Font font = Font.getDefault().derive(Font.BOLD, 9, Ui.UNITS_pt);
titleField.setFont(font);
bitmapField = new BitmapField(DesignSizes.newsIsLoading(),
Field.FIELD_HCENTER);
bitmapField.setPadding(padding);
setBitmap(bean.getImgUrl());
articleField = new RichTextField(parser.clean(bean.getNewsArticle()),
RichTextField.USE_TEXT_WIDTH | RichTextField.TEXT_ALIGN_LEFT
| RichTextField.READONLY);
// bitmap field for the add bitmap
ad = new BitmapField(DesignSizes.adBanner(), Field.FIELD_TRAILING
| Field.FIELD_HCENTER);
// horizontal field manager to set the bitmapfield away from the
// scrollable screen .. as its required to be only
// on the bottom of the screen !
admanager = new HorizontalFieldManager(
VerticalFieldManager.NO_VERTICAL_SCROLL
| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
| Field.FIELD_HALIGN_MASK);
// the other stuff title bar + action bar + itemRow + button more
otherStuff = new VerticalFieldManager(
VerticalFieldManager.VERTICAL_SCROLL) {
protected void sublayout(int maxWidth, int maxHeight) {
// TODO Auto-generated method stub
super.sublayout(maxWidth, maxHeight);
setExtent(maxWidth, Display.getHeight() - ad.getHeight());
}
};
admanager.add(ad);
// font for the article
Font artFont = Font.getDefault().derive(Font.PLAIN, 6, Ui.UNITS_pt);
articleField.setPadding(padding);
articleField.setFont(artFont);
vvv.add(dateField);
vvv.add(titleField);
vvv.add(bitmapField);
vvv.add(articleField);
add(vvv);
add(admanager);
switch (Display.getWidth()) {
case 320:
getAd(adsBean[adCounter].getBlackberry320());
break;
case 360:
getAd(adsBean[adCounter].getBlackberry360());
break;
case 480:
getAd(adsBean[adCounter].getBlackberry480());
break;
case 640:
getAd(adsBean[adCounter].getBlackberry640());
break;
}
}
private void setBitmap(final String url) {
// TODO Auto-generated method stub\\
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
final DownLoadImage dope = new DownLoadImage(url);
bitmap = dope.getImage();
Bitmap resized_bitmap = bitmap;
Bitmap tempbitmap = new Bitmap(Display.getWidth() - 20,
(int) ((Display.getWidth() - 20) * 0.458));
tempbitmap.createAlpha(Bitmap.TRUE_WHITE);
resized_bitmap.scaleInto(tempbitmap, Bitmap.FILTER_LANCZOS);
bitmap = tempbitmap;
bitmapField.setBitmap(bitmap);
}
});
}
protected boolean keyDown(int keycode, int time) {
int key = Keypad.key(keycode);
if (key == Characters.ESCAPE) {
try{
this.time.cancel();
}catch(Exception e){
}
UiApplication.getUiApplication().pushScreen(
new NewsScreen_en(status, tour));
return true;
}
return super.keyDown(keycode, time);
}
// =============================================================================================
// for getting the ads ...
// =============================================================================================
private void loadAD(int timer) {
System.out.println("Timer start! ");
time = new Timer();
task = new TimerTask() {
public void run() {
time.cancel();
switch (Display.getWidth()) {
case 320:
getAd(adsBean[adCounter].getBlackberry320());
break;
case 360:
getAd(adsBean[adCounter].getBlackberry360());
break;
case 480:
getAd(adsBean[adCounter].getBlackberry480());
break;
case 640:
getAd(adsBean[adCounter].getBlackberry640());
break;
}
System.out.println("tik tik tik");
}
};
time.schedule(task, timer * 1000);
}
private void getAd(final String url) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
final DownLoadImage dope = new DownLoadImage(url);
Bitmap bitmap = dope.getImage();
ad.setBitmap(bitmap);
}
});
//for saving more memo
switch(Integer.parseInt(adsBean[adCounter].getAdDuration())){
case 0:
//
break;
default:
System.out.println("loading ad! ");
adCounter++ ;
if(adCounter == adsBean.length || adCounter > adsBean.length){
adCounter = 0;
}
loadAD(Integer.parseInt(adsBean[adCounter].getAdDuration()));
break;
}
}
}
To make your screen scrollable add focusable elements to it. If a screen or its area does not have focusable elements then you will experience problems with scrolling this screen/area.
As an option add empty and focusable separator fields after each non-focusable field. It won't affect on the appearance of your application but will help with scrolling.

Making an object appear to move across the screen randomly

I'm currently doing an assignment, on which one of the requirements is for a random object to appear on screen and move across. Being new to XNA, i do not know where to even begin implementing such behaviours to the game, thus would really appreciate if someone could give me a nudge towards the right direction.
I'm only really accustomed to invoking something when a key is pressed, however with something completely random, this can't be done. as far as i am aware of.
Thank you.
You need to create and set up a sprite for the UFO first. In your protected override void Update(GameTime gameTime) code you simply need to get the current time and compare it to the rules in which you wish to apply. Then update if you wish to draw and "move" the sprite. Here is an example:
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion
public class Game : Microsoft.Xna.Framework.Game {
#region Game Settings
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
GraphicsDevice device;
int screenWidth = 800;
int screenHeight = 600;
bool fullscreen = false;
string title = "MyGame";
string origionaltitle;
float frames = 0;
float framesPerSecond = 0;
int startTime;
int currentTime;
int nextTime;
#endregion
struct sprite {
public string TextureName;
public Texture2D Texture;
public Vector2 Position;
public Vector2 Speed;
public Color[] TextureData;
};
bool DrawUFO = false;
sprite ufo = new sprite();
public Game() {
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent() {
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
device = graphics.GraphicsDevice;
// TODO: use this.Content to load your game content here
ufo.TextureName = "ufo";
ufo.Texture = Content.Load<Texture2D>(ball.TextureName);
ufo.TextureData = new Color[ufo.Texture.Width *ufo.Texture.Height];
ufo.Texture.GetData(ball.TextureData);
}
protected override void Initialize() {
// TODO: Add your initialization logic here
ufo.Position = new Vector2(10f, 10.0f);
ufo.Speed = new Vector2(0.0f, 10.0f);
//
// Set up game window
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
graphics.IsFullScreen = fullscreen;
graphics.ApplyChanges();
origionaltitle = title;
Window.Title = title;
//
// Set the initial time
startTime = DateTime.Now.Second;
//
// Set "random"/next time for ufo to be rendered
nextTime = startTime + rand.Next(2);
//
base.Initialize();
}
protected override void Update(GameTime gameTime) {
//
// Set the current time
currentTime = DateTime.Now.Second;
//
// if not drawing ufo then
if(!DrawURO) {
//
// check current time and compare it with the next time
if( currentTime == nextTime ) {
DrawURO = true;
}
} else {
//
// Update UFO position (aka move it)
ufo.Posistion += ball.Speed *(float)gameTime.ElapsedGameTime.TotalSeconds;
//
// if ufo goes of the screen then
if(ufo.Position.Y > screenHeight) {
//
// Reset ufo
DrawURO = false;
ufo.Position.X = 10.0f;
ufo.Position.Y = 10.0f;
//
// set next time to render
nextTime = currentTime + rand.Next(2);
}
}
}
protected override void Draw(GameTime gameTime) {
graphics.GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
if(DrawUFO == true) {
spriteBatch.Draw(ufo.Texture, ufo.Position, Color.White);
}
spriteBatch.End();
//
base.Draw(gameTime);
}
}
I copied this from some code i did at college a few years a ago, so apologies for any bugs.

Editfield scroll fails to reach top in blackberry

I am having 2 EditFields in my login form with names Email: and Password:. Just below email I have login button. Suppose I come down till login, I can scroll back only till password field.The cursor fails to reach Email field. In simulator, I tried using arrow keys as well as trackpad. Please help how to scroll back to first editfield
AbsoluteFieldManager ab = new AbsoluteFieldManager();
add(ab);
new SeparatorField();
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","");
ab.add(et,35,110);
ab.add(pwd,35,150);
I am using AbsoluteFieldManager and developing for OS 6.0. I want the loginscreen to look like facebook login page.
Kindly let me know what can possibly be the reason for not able to scroll up
Maybe it is a RIM bug with the AbsoluteFieldManager. Never used it before so I don't know about it. You can create a work around to solve this problem. Find it below:
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","") {
protected int moveFocus(int amount, int status, int time) {
int cursorPosition = this.getCursorPosition();
if ((cursorPosition == 0) && (amount < 0)) {
et.setFocus();
return 0;
}
else {
return super.moveFocus(amount, status, time);
}
}
};
In this way, when you arrive to the first element in the password edit field, you will oblige the email field to get focused. This will work for you as a work around.
Another way to solve the problem is to add the two fields in an horizontal field manager, in that way I guess this will work for you for sure. If not use the first method. You can find below the code for HorizontalFieldManager:
et=new EditField("Email-id:","");
pwd=new PasswordEditField("Password:","");
HorizontalFieldManager manager = new HorizontalFieldManager();
manager.add(et);
manager.add(pwd);
ab.add(manager, yourX, yourY);
It also may be a RIM bug. What OS do you use? Is it OS 5+? Do you use custom paddings/margins/borders for some of the UI elements on the screen (including the screen itself)? If yes, try to comment out any code that sets paddings/margins/borders to check whether this it the case.
You can use this code for your login page:
public class loginscreen extends MainScreen implements FieldChangeListener {
private int deviceWidth = Display.getWidth();
private int deviceHeight = Display.getHeight();
private VerticalFieldManager subManager;
private VerticalFieldManager mainManager;
public long mycolor = 0x00FFFFFF;
Screen _screen = home.Screen;
TextField heading = new TextField(Field.NON_FOCUSABLE);
TextField username_ef = new TextField();
PasswordEditField password_ef = new PasswordEditField();
CheckboxField rememberpass = new CheckboxField();
public ButtonField login_bt = new ButtonField("Login", ButtonField.CONSUME_CLICK);
public ButtonField register_bt = new ButtonField("Register", ButtonField.CONSUME_CLICK);
public loginscreen()
{
super();
final Bitmap backgroundBitmap = Bitmap.getBitmapResource("bgd.png");
HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
{
protected void sublayout(int width, int height)
{
Field field;
int numberOfFields = getFieldCount();
int x = 245;
int y = 0;
for (int i = 0;i < numberOfFields;i++)
{
field = getField(i);
setPositionChild(field,x,y);
layoutChild(field, width, height);
x +=_screen.getWidth()-381;
y += 0;//l17
}
width=_screen.getWidth();
height=48;//w19
setExtent(width, height);
}
};
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);
}
public void paint(Graphics graphics)
{
graphics.setColor((int) mycolor);
super.paint(graphics);
}
};
username_ef.setLabel("Username: ");
password_ef.setLabel("Password: ");
rememberpass.setLabel("Remember Password");
heading.setLabel("Please enter your credentials: ");
username_ef.setMaxSize(8);
password_ef.setMaxSize(20);
subManager.add(heading);
subManager.add(username_ef);
subManager.add(password_ef);
subManager.add(rememberpass);
subManager.add(new SeparatorField());
login_bt.setChangeListener(this);
register_bt.setChangeListener(this);
hfm.add(login_bt);
hfm.add(register_bt);
subManager.add(hfm);
mainManager.add(subManager);
this.add(mainManager);
}
public boolean onSavePrompt()
{
return true;
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field == login_bt)
{
//do your code for login button click
}
if(field == register_bt)
{
//code for register button click
}
}}
What you have described is not normal behavior.
My conclusion is that your code has one or more bugs, in order to solve your problem you should modify your code to fix the bugs. You will then be able to scroll up and down through the various fields.
note: As this question stands it's not possible for me to be more specific about the exact bugs. So instead I will show you an example of the layout you described that would scroll properly and you can use as a default to determine which of your deviations have caused your bugs.
// inside MainScreen constructor
add(new EditField("Username:","",0));
add(new EditField("Password:","",0));
add(new ButtonField(buttonBMP,ButtonField.CONSUME_CLICK));

Designing a slot machine in 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.

Resources