BasicEditField Customization - blackberry

I want a basic edit field where the first character entered goes to the right most position ...something like this..
2
23
234
can any one tell me how to do this...

Here's one way to do it:
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.BasicEditField;
public class RightInsertTextField extends BasicEditField {
private String lastGoodTxtInputEntry = null;
private int maxCharInputLength = 20;
private Field nextFieldForFocus = null;
/**
* Basic constructor.
*
* #param defaultValue
*/
public RightInsertTextField(String defaultValue) {
super("", defaultValue);
}
public void paint(Graphics g) {
String txt = this.getText();
// 1. (Optional) keeping a check on input length can help
// minimize custom code needed to handle wrap-around text.
if (txt.length() > this.getMaxCharInputLength() && this.getMaxCharInputLength() > 0) {
txt = this.lastGoodTxtInputEntry;
this.setText(txt);
} else {
this.lastGoodTxtInputEntry = txt;
}
// 2. get rid of the default cursor painting by coloring over it with
// the same color as the background
XYRect xy = g.getClippingRect();
g.setBackgroundColor(Color.WHITE);
g.fillRect(xy.x, xy.y, xy.width, xy.height);
g.clear();
// 3. Align text to the right.
g.setColor(Color.BLACK);
g.drawText(txt, 0, 0, (DrawStyle.RIGHT + DrawStyle.ELLIPSIS), getWidth());
}
/**
* Look out for 'ENTER' being pressed.
*/
public boolean keyChar(char key, int status, int time) {
// Prevent new lines in input field.
if (Characters.ENTER == key) {
if (this.nextFieldForFocus != null) {
this.nextFieldForFocus.setFocus();
}
return true;
} else {
return super.keyChar(key, status, time);
}
}
public void setMaxCharInputLength(int maxCharInputLength) {
this.maxCharInputLength = maxCharInputLength;
}
public int getMaxCharInputLength() {
return maxCharInputLength;
}
/**
* #param nextFieldForFocus
* the nextFieldForFocus to set if 'ENTER' is pressed.
*/
public void setNextFieldForFocus(Field nextFieldForFocus) {
this.nextFieldForFocus = nextFieldForFocus;
}
}

This would help
editField = new EditField("", "", maxChars, EditField.NO_NEWLINE | EditField.NON_SPELLCHECKABLE){
private String text = "";
protected boolean keyChar(char key, int status, int time){
switch (key){
case Characters.BACKSPACE:{
try {
text = text.substring(0,text.length()-1);
invalidate();
} catch (IndexOutOfBoundsException e) {}
return true;
}
}
text = text + key;
invalidate();
return true;
}
protected void paint(Graphics graphics) {
graphics.drawText(text,0, 0, DrawStyle.RIGHT, width - 10);
super.paint(graphics);
}
};

Use style Field.FIELD_RIGHT.

Pretty sure that there is no built in way to do this, you gona have to implement your own text box

Related

Blackberry scrolling doesn't redraw fields

I have a very strange problem at the moment.
Basically when I scroll in a screen, the fields don't get redrawn completely or consistently.
I have a Screen (NO_VERTICAL_SCROLL), with a manager as a titlebar. Below that I have a vertical field manager (VERTICAL_SCROLL) with labelfields. When I scroll the vfm one or two lines of the labelfields, which were already visible, get redrawn. The section I'm scrolling down to has absolutely nothing drawn.
I tried invalidate(), and calling doPaint in a scrollchangelistener, but its actually much worse. It results in the titlebar only being partially redrawn.
In the code below I used a custom FontManager, DimenManager, and ImageResourceManager to return values dependent on screen size. I used a custom BitmapButtonField and ClickableLabel in order to change the state of a field when a click is being held in.
public class BaseScreen extends MainScreen implements StringsResource
{
protected ResourceBundle resources;
public BaseScreen(long style)
{
super(style);
StandardTitleBar titlebar = new StandardTitleBar();
titlebar.addSignalIndicator();
titlebar.addClock();
titlebar.addNotifications();
setTitle(titlebar);
resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);
}
}
public class TandCScreen extends BaseScreen
{
final String copy_text1 = "long text here";
final String copy_text2 = "even longer text here";
ColoredLabelField label_title;
ColoredLabelField label_subtitle;
ColoredLabelField label1;
ColoredLabelField label2;
ClickableLabel label3;
public TandCScreen()
{
super(NO_VERTICAL_SCROLL | NO_VERTICAL_SCROLLBAR);
label_title = new ColoredLabelField(resources.getString(STRING_APP_NAME), Color.WHITE, DrawStyle.HCENTER | USE_ALL_WIDTH);
label_title.setBackground(BackgroundFactory.createSolidBackground(0x60223b));
label_subtitle = new ColoredLabelField(resources.getString(STRING_TANDC_TITLE), 0x58585b, DrawStyle.HCENTER | USE_ALL_WIDTH);
label1 = new ColoredLabelField(copy_text1, 0x58585b, USE_ALL_WIDTH);
label2 = new ColoredLabelField("", 0xa7a9ab, USE_ALL_WIDTH);
label3 = new ClickableLabel("Read more...")
{
protected void unclick()
{
super.unclick();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
ColoredLabelField label = new ColoredLabelField(copy_text2, 0xa7a9ab, 0);
label.setFont(FontManager.body());
label.setMargin(0, 0, DimenManager.interField(), 0);
label2.getManager().replace(label2, label);
label3.getManager().delete(label3);
}
});
}
};
label_title.setFont(FontManager.subtitle());
label_subtitle.setFont(FontManager.subtitle());
label1.setFont(FontManager.body());
label2.setFont(FontManager.body());
label3.setFont(FontManager.body());
BitmapButtonField button_accept = new BitmapButtonField(ImageResourceManager.buttonAccept(), ImageResourceManager.buttonAcceptHover(), FIELD_HCENTER)
{
protected void click()
{
super.click();
setImage(ImageResourceManager.buttonAcceptSelected());
setFocusImage(ImageResourceManager.buttonAcceptSelected());
}
protected void unclick()
{
super.unclick();
PersistentStoreManager.setTandCAccepted(true);
UiApplication.getUiApplication().pushScreen(new LoginScreen());
close();
}
};
BitmapButtonField button_decline = new BitmapButtonField(ImageResourceManager.buttonDecline(), ImageResourceManager.buttonDeclineHover(), FIELD_HCENTER)
{
protected void click()
{
super.click();
setImage(ImageResourceManager.buttonDeclineSelected());
setFocusImage(ImageResourceManager.buttonDeclineSelected());
}
protected void unclick()
{
super.unclick();
close();
}
};
int margin = (VariableManager.DISPLAY_WIDTH - button_accept.getPreferredWidth()) / 2;
// calculate where to put ellipsis
Font font = label2.getFont();
int max_length = (VariableManager.DISPLAY_WIDTH - margin * 2) * 2;
int i = copy_text2.length() - 1;
while (font.getAdvance(copy_text2.substring(0, i)) + font.getAdvance("...") >= max_length)
i--;
label2.setText(copy_text2.substring(0, i).trim() + "...");
VerticalFieldManager vfm = new VerticalFieldManager(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
vfm.add(new NullField());
vfm.add(label_subtitle);
vfm.add(new Seperator());
vfm.add(label1);
vfm.add(label2);
vfm.add(label3);
vfm.add(button_accept);
vfm.add(button_decline);
vfm.setMargin(0, margin, 0, margin);
// paddings
int padding = (DimenManager.header() - label_title.getPreferredHeight()) / 2;
label_title.setPadding(padding, 0, padding, 0);
label_subtitle.setPadding(DimenManager.interField(), 0, DimenManager.interField(), 0);
label1.setMargin(DimenManager.interField(), 0, DimenManager.interField(), 0);
label3.setMargin(DimenManager.interField(), 0, DimenManager.interField(), button_accept.getPreferredWidth() - label3.getPreferredWidth());
button_decline.setMargin(DimenManager.interField(), 0, DimenManager.interButton(), 0);
add(label_title);
add(vfm);
}
protected boolean onSavePrompt()
{
return false;
}
protected void makeMenu(Menu menu, int instance)
{
if (instance == Menu.INSTANCE_CONTEXT)
{
ContextMenu contextMenu = ContextMenu.getInstance();
contextMenu.setTarget(this);
contextMenu.clear();
this.makeContextMenu(contextMenu);
menu.deleteAll();
menu.add(contextMenu);
}
else
{
super.makeMenu(menu, instance);
}
}
protected void makeContextMenu(ContextMenu contextMenu)
{
}
/**
* Clickable labelfield which changes color on down press, and fires action
* on release. Action is canceled if touch moves outside field bounds.
*
* #author kevin
*
*/
private class ClickableLabel extends LabelField
{
private boolean canceled = true;
private boolean consumed = false;
protected boolean pressed = false;
public ClickableLabel(String label)
{
super(label, LabelField.FOCUSABLE | USE_ALL_WIDTH);
setFont(FontManager.body());
}
protected void paint(Graphics g)
{
// background
if (pressed)
{
g.setColor(0x2C1721);
}
else if (isFocus())
{
g.setColor(0x993C6B);
}
else
{
g.setColor(0x60223B);
}
int padding_y = (getPreferredHeight() - getFont().getHeight()) / 2;
int padding_x = getPaddingLeft();
g.drawText(getText(), padding_x, padding_y);
}
public int getPreferredHeight()
{
return ImageResourceManager.highlight().getHeight();
}
protected void layout(int width, int height)
{
height = getPreferredHeight();
super.layout(width, height);
setExtent(width, height);
}
// --------- Highlight selected row ---------
protected void onFocus(int direction)
{
super.onFocus(direction);
invalidate();
}
protected void onUnfocus()
{
super.onUnfocus();
invalidate();
}
// --------------------------------------------
protected void drawFocus(Graphics graphics, boolean on)
{
}
/**
* Called when trackpad pressed, or touchscreen touched
*/
protected void click()
{
pressed = true;
invalidate();
}
/**
* Called when trackpad released, or touchscreen released
*/
protected void unclick()
{
cancel();
}
protected void cancel()
{
pressed = false;
invalidate();
}
protected boolean navigationClick(int status, int time)
{
if (status != 0)
{
if (consumed)
{
consumed = false;
}
else
{
click();
}
}
return true;
}
protected boolean navigationUnclick(int status, int time)
{
if (status != 0)
{
if (consumed)
consumed = false;
else
unclick();
}
return true;
}
protected boolean touchEvent(TouchEvent message)
{
int x = message.getX(1);
int y = message.getY(1);
if (x < 0 || y < 0 || x > getExtent().width || y > getExtent().height)
{
// Outside the field
if (!canceled)
{
cancel();
}
canceled = true;
return false;
}
if (message.getEvent() == TouchEvent.UP)
{
if (canceled)
cancel();
else
unclick();
consumed = true;
return true;
}
if (message.getEvent() == TouchEvent.DOWN)
{
click();
consumed = true;
canceled = false;
return true;
}
return super.touchEvent(message);
}
}
private class Seperator extends SeparatorField
{
protected void paint(Graphics graphics)
{
graphics.setColor(0xa7a9ab);
super.paint(graphics);
}
}
}
Thanks in advance for any suggestions
I don't think it is possible to do anything but guess at your problem without looking at your code. But whatever your problem is, I am confident that it is based on a misunderstanding of how to use Managers within a Screen. So I recommend that you review the following articles to improve your knowledge in this area and so hopefully resolve the problem yourself:
Start here:
UI Introduction
This provides the Background around Managers and Fields.
Then read this article:
MainScreen Explained
I suspect as a result of reading this article, you may be able to discard your 'title bar' and use setTitle() or setBanner() to provide this function.
I hope this resolves your problems.
A few other points:
In all my years of BB programming, I have never had to use doPaint() to get something painting the way I wanted. I can't think of a situation that this will in fact help. So if you think you need it, try invalidate() instead.
I have used invalidate() when I making a change to the Field that will change its on screen appearance (but not its size). I have used it in a scroll change listener. But it is a method of last resort.
Remember that LabelFields are not focusable, so in OS's before 6, that made them a problem to scroll.
Found the issue. On the labelfields, there was a setExtent(getPreferredWidth(), getPreferredHeight()); that was reducing the size of the area to redraw. Very stupid mistake.
Thanks to everyone who tried to help.

BlackBerry - Set the text width of a EditField from a changeListener event

If the length returned by input.getText() is greater than 13, the last character entered by the user should not appear on the edit field. If the 13th character is a ',' the program should allow 2 additional characters after the ','. That way, the maximum length of the edit field would be 16.
What would be an option to limit the text width of an EditField like this?
input = new BorderedEditField();
input.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(input.getText().length() < 13)
input.setText(pruebaTexto(input.getText()));
else
//do not add the new character to the EditField
}
});
public static String pruebaTexto(String r){
return r+"0";
}
I have coded a simple BorderedEditField class which extends EditField. The method, protected boolean keyChar(char key, int status, int time) of this class gets modified so that manipulation of EditField's default behavior is possible. If you found this example helpful, then you can improve the implementation.
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen {
public MyScreen() {
BorderedEditField ef = new BorderedEditField();
ef.setLabel("Label: ");
add(ef);
}
}
class BorderedEditField extends EditField {
private static final int MAX_LENGTH = 13;
private static final int MAX_LENGTH_EXCEPTION = 16;
private static final char SPECIAL_CHAR = ',';
protected boolean keyChar(char key, int status, int time) {
// Need to add more rules here according to your need.
if (key == Characters.DELETE || key == Characters.BACKSPACE) {
return super.keyChar(key, status, time);
}
int curTextLength = getText().length();
if (curTextLength < MAX_LENGTH) {
return super.keyChar(key, status, time);
}
if (curTextLength == MAX_LENGTH) {
char spChar = getText().charAt(MAX_LENGTH - 1);
return (spChar == SPECIAL_CHAR) ? super.keyChar(key, status, time) : false;
}
if (curTextLength > MAX_LENGTH && curTextLength < MAX_LENGTH_EXCEPTION) {
return super.keyChar(key, status, time);
} else {
return false;
}
}
}

How to get multiple selected list items from list field checkbox and add into an arraylist in blackberry

Please anyone help me get selected listitems from a listfieldcheckbox, and add them into an arraylist. If possible, give any useful links also. Here's my code so far (I am new to blackberry application development). Please help.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.IntVector;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements ListFieldCallback
{
private Vector _listData = new Vector();
private Vector _checkedData = new Vector();
private ListField listField;
private static final String[] _elements = {"First element", "Second element","Third element"
};
//private static final String[] _elements1 = {"hai","welcome","where r u"
//};
private MenuItem _getDataMenu,selectall,Delete;
Vector result = new Vector();
protected void makeMenu(Menu menu, int instance)
{
menu.add(_getDataMenu);
menu.add(selectall);
menu.add(Delete);
//Create the default menu.
super.makeMenu(menu, instance);
}
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
public Vector getCheckedItems() {
return _checkedData;
}
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
VerticalFieldManager main = new VerticalFieldManager(VerticalFieldManager.USE_ALL_HEIGHT|
VerticalFieldManager.USE_ALL_WIDTH|VerticalFieldManager.VERTICAL_SCROLL);
this.add(main);
HorizontalFieldManager hfm = new HorizontalFieldManager();
main.add(hfm);
listField = new ListField(){
//Allow the space bar to toggle the status of the selected row.
protected boolean keyChar(char key, int status, int time)
{
boolean retVal = false;
//If the spacebar was pressed...
if (key == Characters.SPACE)
{
//Get the index of the selected row.
int index = getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
invalidate(index);
//Consume this keyChar (key pressed).
retVal = true;
}
return retVal;
}
};
listField.setCallback(this);
reloadList();
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.addElement(new ChecklistData(_elements[count], false));
//_listData.addElement(new ChecklistData(_elements1[count], false));
listField.insert(count);
}
main.add(listField);
_getDataMenu =new MenuItem("Get Data", 200, 10) {
public void run(){
int index = listField.getSelectedIndex();
ChecklistData data = (ChecklistData)_listData.elementAt(index);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
//Dialog.alert(message);
// get all the checked data indices
IntVector selectedIndex = new IntVector(0, 1);
//ChecklistData data;
for (int i=0;i<_listData.size();i++) {
data = (ChecklistData)_listData.elementAt(i);
if(data.isChecked()) {
selectedIndex.addElement(i);
String selectedvalues = data.getStringVal();
System.out.println("Selected items are:"+selectedvalues);
}
}
data = null;
// now selectedIndex will contain all the checked data indices.
//String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
}
};
selectall = new MenuItem("Selectall", 200, 10){
public void run(){
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.setElementAt(new ChecklistData(_elements[count], true), count);
}
}
};
Delete = new MenuItem("Delete", 200, 10){
public void run(){
int index = listField.getSelectedIndex();
_listData.removeElementAt(index);
// update the view
listField.delete(index);
listField.invalidate(index);
}
};
}
private void reloadList() {
// TODO Auto-generated method stub
_listData.setSize(_listData.size());
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*if (currentRow.isChecked()) {
if( -1 ==_checkedData.indexOf(currentRow))
_checkedData.addElement(currentRow);
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else {
if( -1 !=_checkedData.indexOf(currentRow))
_checkedData.removeElement(currentRow);
rowString.append(Characters.BALLOT_BOX);
} */
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
}
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
return _listData.indexOf(p, s);
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
protected boolean navigationClick(int status, int time) {
int index1 = listField.getSelectedIndex();
/*System.out.println("Selected item index:"+index1);
//int[] list =listField.getSelection();
//String s = Integer.toString(list);
System.out.println(" items are:"+_elements[index1]);
//ChecklistData data = (ChecklistData)_listData.elementAt(index1);*/
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index1);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
System.out.println("message is:"+message);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index1);
//Invalidate the modified row of the ListField.
listField.invalidate(index1);
return true;
}
}

Blackberry UI Hint Box

I am very much new to the blackberry UI development and want to know that is there any way you can add a hint box on bitmap? just like a title attribute in an element of HTML
You can use the following TooltipScreen and add fields to the screen in the following way
add(new ButtonField(“myButton”), “My Tooltip text”);
TooltipScreen
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.container.MainScreen;
public class TooltipScreen extends MainScreen {
TooltipScreen screen = this;
boolean doRedraw = false;//prevent infinte redrawing
Vector tooltips = new Vector();//vector to hold tooltip strings
private Timer tooltipTimer = new Timer();
private TimerTask tooltipTask;
boolean alive = false;//is the tooltip alive? used to pop it after our timeout
int count = 0;//used to calculate time tooltip is displayed
//tooltip popup colours:
int backgroundColour = 0xeeeeee;
int borderColour = 0xaaaaaa;
int fontColour = 0x666666;
//the tooltip:
String tooltip;
int tooltipWidth;
int yCoord;
int xCoord;
//region parameters:
XYRect contentArea;
int contentBottom;
int contentRight;
public TooltipScreen() {
super();
//when timeout reaches 100ms*20 ie. 2seconds set alive to false and redraw screen:
tooltipTask = new TimerTask() {
public void run() {
if (alive) {
count++;
if (count == 20) {
alive = false;
invalidate();
}
}
}
};
tooltipTimer.scheduleAtFixedRate(tooltipTask, 100, 100);
}
//override add method adds an empty string to tooltip vector:
public void add(Field field) {
tooltips.addElement("");
super.add(field);
}
//custom add method for fields with tooltip: add(myField, "myTooltip");
public void add(Field field, String tooltip) {
super.add(field);
tooltips.addElement(tooltip);
}
public void setColours(int backgroundColour, int borderColour, int fontColour) {
this.backgroundColour = backgroundColour;
this.borderColour = borderColour;
this.fontColour = fontColour;
}
//reset everything when user changes focus,
//possibly needs logic to check field has actually changed (for listfields, objectchoicefields etc etc)
protected boolean navigationMovement(int dx, int dy, int status, int time) {
count = 0;
alive = true;
doRedraw = true;
return super.navigationMovement(dx, dy, status, time);
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (alive) {
Field focusField = getFieldWithFocus();
tooltip = (String) tooltips.elementAt(screen.getFieldWithFocusIndex());
//don't do anything outside the norm unless this field has a tooltip:
if (!tooltip.equals("")) {
//get the field content region, this may fall inside the field actual region/coordinates:
contentArea = focusField.getContentRect();
contentBottom = contentArea.y + contentArea.height;
contentRight = contentArea.x + contentArea.width;
//+4 to accomodate 2 pixel padding on either side:
tooltipWidth = graphics.getFont().getAdvance(tooltip) + 4;
yCoord = contentBottom - focusField.getManager().getVerticalScroll();
//check the tooltip is being drawn fully inside the screen height:
if (yCoord > (getHeight() - 30)) {
yCoord = getHeight() - 30;
}
//check the tooltip doesn't get drawn off the right side of the screen:
if (contentRight + tooltipWidth < getWidth()) {
xCoord = contentRight;
} else {
xCoord = getWidth() - tooltipWidth;
}
//draw the tooltip
graphics.setColor(backgroundColour);
graphics.fillRect(xCoord, yCoord, tooltipWidth, 30);
graphics.setColor(borderColour);
graphics.drawRect(xCoord, yCoord, tooltipWidth, 30);
graphics.setColor(fontColour);
graphics.drawText(tooltip, xCoord + 2, yCoord);
}
}
//doRedraw logic prevents infinite loop
if (doRedraw) {
//System.out.println("redrawing screen: " + System.currentTimeMillis());
screen.invalidate();
doRedraw = false;
}
}
}

Image Button in BlackBerry

How do I implement an image button in BlackBerry?
here you go, complete code:
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
/**
* Button field with a bitmap as its label.
*/
public class BitmapButtonField 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 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;
}
/* (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);
}
public void setHighlight(boolean highlight)
{
this.highlighted = highlight;
}
}
Use RIM's Advanced UI Pack.
http://supportforums.blackberry.com/t5/Java-Development/Implement-advanced-buttons-fields-and-managers/ta-p/488276
This contains a BitmapButton field and a great number of of useful UI tools.
(No doubt Reflogs example is good, but I think for new BB developers landing on this page the Advanced UI pack is more beneficial)
perfect ImageButton for Blackberry , According to user point of view a Imagebutton should have four states
1. Normal
2. Focus
3. Selected Focus
4. Selected unfocus
the Following code maintain all four states (Field-Change-Listener and Navigation)
if you want to maintain all four states than use 1st Constructor, If you just want to handle Focus/Un-Focu state of the button than use 2nd one
########################################
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class ImageButton extends Field
{
Bitmap mNormalIcon;
Bitmap mFocusedIcon;
Bitmap mActiveNormalIcon;
Bitmap mActiveFocusedIcon;
Bitmap mActiveBitmap;
String mActiveText;
int mHeight;
int mWidth;
boolean isStateActive = false;
boolean isTextActive = false;
public boolean isStateActive()
{
return isStateActive;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveBitmap = normalIcon;
mActiveFocusedIcon = focusedIcon;
mActiveNormalIcon = normalIcon;
// isTextActive = false;
}
public ImageButton(Bitmap normalIcon, Bitmap focusedIcon, Bitmap activeNormalIcon, Bitmap activeFocusedIcon)
{
super(Field.FOCUSABLE | FIELD_VCENTER);
mNormalIcon = normalIcon;
mFocusedIcon = focusedIcon;
mActiveFocusedIcon = activeFocusedIcon;
mActiveNormalIcon = activeNormalIcon;
mActiveBitmap = normalIcon;
// isTextActive = true;
}
protected void onFocus(int direction)
{
if ( !isStateActive )
{
mActiveBitmap = mFocusedIcon;
}
else
{
mActiveBitmap = mActiveFocusedIcon;
}
}
protected void onUnfocus()
{
super.onUnfocus();
if ( !isStateActive )
{
mActiveBitmap = mNormalIcon;
}
else
{
mActiveBitmap = mActiveNormalIcon;
}
}
protected boolean navigationClick(int status, int time)
{
mActiveBitmap = mActiveNormalIcon;
toggleState();
invalidate();
fieldChangeNotify(1);
return true;
}
public void toggleState()
{
isStateActive = !isStateActive;
}
public int getPreferredWidth()
{
return mActiveBitmap.getWidth() + 20;
}
public int getPreferredHeight()
{
return mActiveBitmap.getHeight() + 10;
}
protected void layout(int width, int height)
{
mWidth = getPreferredWidth();
mHeight = getPreferredHeight();
setExtent(mWidth, mHeight);
}
protected void paint(Graphics graphics)
{
graphics.drawBitmap(0, 5, mWidth, mHeight, mActiveBitmap, 0, 0);
// graphics.setColor(0xff0000);
// graphics.drawText(mActiveText, ( mActiveBitmap.getWidth() -
// this.getFont().getAdvance("ON") ) / 2, mActiveBitmap.getHeight());
}
protected void drawFocus(Graphics graphics, boolean on)
{
}
public void activate()
{
mActiveBitmap = mActiveNormalIcon;
isStateActive = true;
invalidate();
}
public void deactivate()
{
mActiveBitmap = mNormalIcon;
isStateActive = false;
invalidate();
}
}
easiest way to do that:
step 1:draw a image with specific coordinates(imageX,imageY).
step 2:add a method in your Code:
void pointerControl(int x, int y) {
if (x>imageX && x<imageX+imageName.getWidth() && y>imageY && y < imageY+imageName.getHeight) {
//to do code here
}
}
where imageName:name of image
imageX=x coordinate of image(Top-Left)
imageY=y coordinate of image(Top-Left)

Resources