Collision Detection, Player with tiles of the map - xna
How do I to make a collision with a tile from the map with my player?
Animation class:
public class Animation
{
public float speed = 2.5f;
protected string currentAnimatie;
public Texture2D sTexture;
public Vector2 sPosition;
private int FrameIndex;
private double TimeElapse;
private double TimeToUpdate;
public Vector2 sDirection = Vector2.Zero;
public Rectangle BoxRondCharachter
{
get
{
return new Rectangle((int)sPosition.X, (int)sPosition.Y, 50, 41);
}
}
public int FramesPerSec
{
set { TimeToUpdate = (1f / value); }
}
public Animation(Vector2 pos)
{
sPosition = pos;
}
public void Update(GameTime gametime)
{
TimeElapse += gametime.ElapsedGameTime.TotalSeconds;
if (TimeElapse > TimeToUpdate)
{
TimeElapse -= TimeToUpdate;
if (FrameIndex < sAnimatie[currentAnimatie].Length - 1)
{
FrameIndex++;
}
else
{
FrameIndex = 0;
}
TimeElapse = 0;
}
sPosition += sDirection;
sDirection = Vector2.Zero;
}
public void AddAnimatie(int frames, double yPos, int xStart, string naam, int width, int height, Vector2 offset)
{
Rectangle[] Rectangles = new Rectangle[frames];
///neemt de spritesheet en het verdeelt zich
for (int i = 0; i < frames; i++)
{
Rectangles[i] = new Rectangle((i + xStart) * width, (int)yPos, width, height);
}
sAnimatie.Add(naam, Rectangles);
}
public void Draw(SpriteBatch sprite)
{
sprite.Draw(sTexture, sPosition, sAnimatie[currentAnimatie [FrameIndex], Color.White);
}
public void AnimatieAfspelen(string animatieNaam)
{
if (currentAnimatie != animatieNaam)
{
currentAnimatie = animatieNaam;
FrameIndex = 0;
}
}
public void LaadContent(ContentManager content)
{
sTexture = content.Load<Texture2D>("char");
}
}
MapEngine Class:
class MapEngine
{
private List<CollisionTiles> collisionTiles = new List<CollisionTiles>();
public List<CollisionTiles> CollisionTiles
{
get { return collisionTiles; }
}
private int width, height;
public int Width
{
get { return width; }
}
public int Height
{
get { return height; }
}
public MapEngine()
{
}
public void Generate(int[,] map, int size)
{
for (int x = 0; x < map.GetLength(1); x++)
{
for (int y = 0; y < map.GetLength(0); y++)
{
int number = map[y, x];
if (number > 0)
{
collisionTiles.Add(new CollisionTiles(number, new Rectangle(x * size, y * size, size, size)));
width = (x + 1) * size;
height = (y + 1) * size;
}
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (CollisionTiles tile in collisionTiles)
{
tile.Draw(spriteBatch);
}
}
}
Map class:
class Map : MapEngine
{
public void ShowMap(ContentManager Content)
{
Tiles.Content = Content;
Generate(new int[,]{
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},
{2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,},
{2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2,},
{2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2,},
{2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2,},
{2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2,},
{2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,},
{2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,}
}, 74);
}
}
Hero class:
public class Hero
{
private Vector2 position = new Vector2(54, 485);
public Vector2 Position
{
get { return position; }
}
public int Width { get; set; }
public int Height { get; set; }
private Animation _animation;
private Inputs inputH = new Inputs();
public bool LinkseStand = false;
private Rectangle collisionRectangle;
public Rectangle CollisionRectangle
{
get => collisionRectangle;
set => collisionRectangle = value;
}
public Hero()
{
_animation = new Animation(position);
_animation.AddAnimatie(4, 0, 0, "RechteIdle", 50, 35, new Vector2(0, 0));
_animation.AddAnimatie(4, 34, 0, "LinkseIdle", 50, 35, new Vector2(0, 0));
_animation.AddAnimatie(6, 72, 0, "Right", 50, 34, new Vector2(0, 0));
_animation.AddAnimatie(6, 107, 0, "Left", 50, 40, new Vector2(0, 0));
_animation.AddAnimatie(9, 144, 0, "Jump", 46, 41, new Vector2(0, 0));
_animation.AddAnimatie(4, 220, 0, "Crouch", 50, 32, new Vector2(0, 0));
_animation.AddAnimatie(7, 255, 0, "FirstAttack", 50, 45, new Vector2(0, 0));
_animation.AddAnimatie(14, 300, 0, "ComboAttack", 50, 41, new Vector2(0, 0));
_animation.AddAnimatie(5, 300, 0, "Dood", 50, 41, new Vector2(0, 0));
_animation.AnimatieAfspelen("RechteIdle");
_animation.FramesPerSec = 8;
}
public void Draw(SpriteBatch spritebatch)
{
_animation.Draw(spritebatch);
}
public void laadContent(ContentManager content)
{
_animation.LaadContent(content);
}
public void Update(GameTime gameTime)
{
_animation.Update(gameTime);
position += _animation.sDirection;
CollisionRectangle = new Rectangle((int)_animation.sPosition.X, (int)_animation.sPosition.Y, 50, 41);
inputH.update();
Move(gameTime);
}
private void Move(GameTime gameTime)
{
if (inputH.Right)
{
_animation.AnimatieAfspelen("Right");
_animation.sDirection.X = _animation.speed;
LinkseStand = false;
}
else if (inputH.Left)
{
_animation.AnimatieAfspelen("Left");
_animation.sDirection.X -= _animation.speed;
LinkseStand = true;
}
else if (inputH.Up)
{
_animation.AnimatieAfspelen("Jump");
_animation.sDirection.Y -= _animation.speed;
}
else if (inputH.NormalAttack)
{
_animation.AnimatieAfspelen("FirstAttack");
}
else if (inputH.ComboAttack)
{
_animation.AnimatieAfspelen("ComboAttack");
}
else
{
if (LinkseStand == true)
_animation.AnimatieAfspelen("LinkseIdle");
else
_animation.AnimatieAfspelen("RechteIdle");
}
}
}
Collision tile class:
class CollisionTiles : Tiles
{
public CollisionTiles(int i, Rectangle newRect)
{
texture = Content.Load<Texture2D>("Tile" + i); //loads the tile (tile1, tile2)
Rectangle = newRect;
}
}
Game1 class:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D background;
Vector2 backPos;
Animation _ani;
Hero _hero;
Map map;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1000; // set this value to the desired width of your window
graphics.PreferredBackBufferHeight = 590; // set this value to the desired height of your window
graphics.ApplyChanges();
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
map = new Map();
_hero = new Hero();
_ani = new Animation(_hero.Position);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
background = Content.Load<Texture2D>("background1");
backPos = new Vector2(0, 0);
map.ShowMap(Content);
//_heroTexture = Content.Load<Texture2D>("idleStand");
_hero.laadContent(Content);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
_hero.Update(gameTime);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Cyan);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(background, backPos, Color.White);
map.Draw(spriteBatch);
_hero.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
You can pass the Map instance to the Hero in the Update method in Game1:
_hero.Update(gameTime, map);
And use that to loop through the map.CollisionTiles list checking for overlaps in the Hero class:
public void Update(GameTime gameTime, Map map)
{
_animation.Update(gameTime);
position += _animation.sDirection;
CollisionRectangle = new Rectangle((int)_animation.sPosition.X, (int)_animation.sPosition.Y, 50, 41);
// Check for collision with any of the CollisionTiles:
foreach(var item in map.CollisionTiles)
if(item.Rectangle.Intersects(CollisionRectangle))
// ^^^^^^^^^ needs to be public in the tile class.
{
position -= _animation.sDirection; // Collided with a tile undo move
break; //prevent moving backwards if colliding with more than one tile
}
inputH.update();
Move(gameTime);
}
In this code, the Hero is prevented from moving onto any CollisionTile.
Related
In Listfield not able to view the fields in blackberry
i have tried this link How to customize a ListField in BlackBerry? to create the ListField with Three lablefields for every list row.but iam not able see the list field items.but i can say that listfield is added.because on navigation click i am able get the selected index of the listfield.please anybody help where iam doing mistake.The code i have tried is... public class InboxWithOutCheckboxeslistfield extends ListField implements ListFieldCallback { private Vector rows; private TableRowManager row ; private LabelField UserName,Message,Timestamp; /** * Creates a new MyScreen object */ public InboxWithOutCheckboxeslistfield() { // TODO Auto-generated constructor stub super(0, ListField.MULTI_SELECT); setRowHeight(80); setCallback(this); rows = new Vector(); for (int x = 0; x < 10; x++) { row = new TableRowManager(); UserName = new LabelField("" + String.valueOf(x), DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.LEFT); UserName.setText("name"); row.add(UserName); Message = new LabelField("" + String.valueOf(x), DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.RIGHT); Message.setText("hai"); row.add(Message); Timestamp = new LabelField("" + String.valueOf(x), DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.RIGHT); Timestamp.setText("hai"); row.add(Timestamp); rows.addElement(row); } setSize(rows.size()); } public void drawListRow(ListField listField, Graphics graphics, int index, int y, int width) { // TODO Auto-generated method stub InboxWithOutCheckboxeslistfield list = (InboxWithOutCheckboxeslistfield) listField; TableRowManager rowManager = (TableRowManager) list.rows.elementAt(index); rowManager.drawRow(graphics, 0, y, width, list.getRowHeight()); } public Object get(ListField listField, int index) { // TODO Auto-generated method stub return null; } public int getPreferredWidth(ListField listField) { // TODO Auto-generated method stub return 0; } public int indexOfList(ListField listField, String prefix, int start) { // TODO Auto-generated method stub return 0; } private class TableRowManager extends Manager { protected TableRowManager(){super(0); // TODO Auto-generated constructor stub} } public void drawRow(Graphics graphics, int i, int y, int width, int rowHeight) { // TODO Auto-generated method stub // Arrange the cell fields within this row manager. layout(width, rowHeight); // Place this row manager within its enclosing list. setPosition(i, y); // Apply a translating/clipping transformation to the graphics // context so that this row paints in the right area. graphics.pushRegion(getExtent()); // Paint this manager's controlled fields. subpaint(graphics); graphics.setColor(0x00CACACA); graphics.drawLine(0, 0, getPreferredWidth(), 0); // Restore the graphics context. graphics.popContext(); } protected void sublayout(int width, int height) { // TODO Auto-generated method stub // set the size and position of each field. int fontHeight = Font.getDefault().getHeight(); int preferredWidth = getPreferredWidth(); Field field = getField(0); layoutChild(field, preferredWidth - 16, fontHeight + 1); setPositionChild(field, 34, 3); // set the list name label field field = getField(1); layoutChild(field, 150, fontHeight + 1); setPositionChild(field, 34, fontHeight + 6); // set the due time name label field field = getField(2); layoutChild(field, 150, fontHeight + 1); setPositionChild(field, preferredWidth - 152, fontHeight + 6); setExtent(getPreferredWidth(), getPreferredHeight()); } // The preferred width of a row is defined by the list renderer. public int getPreferredWidth() { return getWidth(); } // The preferred height of a row is the "row height" as defined in the // enclosing list. public int getPreferredHeight() { return getHeight(); } } protected boolean navigationClick(int status, int time) { int index1 = getSelectedIndex(); System.out.println("The Clikced item is:"+index1); return true; } } and the mainscreen class is public class InboxWithOutCheckboxes extends MainScreen{ private InboxWithOutCheckboxeslistfield inboxWithOutCheckboxeslistfield; public InboxWithOutCheckboxes(){ super(); inboxWithOutCheckboxeslistfield = new InboxWithOutCheckboxeslistfield(); add(inboxWithOutCheckboxeslistfield); add(new SeparatorField()); } }
Try This code - Add lists on Main Screen- InboxWithOutCheckboxeslistfield InboxWithOutCheckboxeslistfield = new InboxWithOutCheckboxeslistfield (); add(InboxWithOutCheckboxeslistfield ); add(new SeparatorField()); Click event listener of list - protected boolean navigationClick(int status, int time) { getValue(); return true; } protected void getValue() { Field f = getFieldWithFocus(); if (f instanceof ListField) { ListField l = (ListField) f; final int index = l.getSelectedIndex(); FriendsRequestObject _contactslist = (FriendsRequestObject) FriendsRequest_fields.vector.elementAt(index); final String _name = _contactslist.getSender_name(); final String _id = _contactslist.getSender_id(); //Dialog.alert(_name); Application.getApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(_name); } }); // Dialog.alert("The selected element is: "+Integer.toString(l.getSelectedIndex())); } } import java.util.Vector; 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.Font; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; class InboxWithOutCheckboxeslistfield extends ListField implements ListFieldCallback { private Vector contacts; static Vector vector = new Vector(); private int contactslist_size = 0; private String name_ = "", id_="", status_=""; public InboxWithOutCheckboxeslistfield () { super(0, ListField.MULTI_SELECT); setRowHeight(60); setEmptyString("Empty List", DrawStyle.HCENTER); setCallback(this); contacts = new Vector(); vector.addElement(new FriendsRequestObject("1", "hai1", "")); vector.addElement(new FriendsRequestObject("2", "hai2", "")); vector.addElement(new FriendsRequestObject("3", "hai3", "")); vector.addElement(new FriendsRequestObject("4", "hai4", "")); contactslist_size = vector.size(); for (int x = 0; x < contactslist_size; x++) { FriendsRequestObject b = (FriendsRequestObject) vector.elementAt(x); id_ = b.getSender_id().toString(); name_ = b.getSender_name().toString(); status_ = b.getimage().toString(); TableRowManager row = new TableRowManager() { public void paint(Graphics g) { g.setBackgroundColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); g.clear(); super.paint(g); } }; LabelField name1 = new LabelField(id_, DrawStyle.ELLIPSIS); name1.setFont(Font.getDefault().derive(Font.PLAIN)); row.add(name1); LabelField name = new LabelField(name_, DrawStyle.ELLIPSIS); name.setFont(Font.getDefault().derive(Font.PLAIN)); row.add(name); // add to the table contacts.addElement(row); } setSize(contacts.size()); } // ListFieldCallback Implementation public void drawListRow(ListField listField, Graphics g, int index, int y, int width) { InboxWithOutCheckboxeslistfield list = (InboxWithOutCheckboxeslistfield ) listField; TableRowManager rowManager = (TableRowManager) list.contacts.elementAt(index); rowManager.drawRow(g, 0, y, width, list.getRowHeight()); } private class TableRowManager extends Manager { public TableRowManager() { super(0); } // Causes the fields within this row manager to be layed out then // painted. public void drawRow(Graphics g, int x, int y, int width, int height) { // Arrange the cell fields within this row manager. layout(width, height); // Place this row manager within its enclosing list. setPosition(x, y); // Apply a translating/clipping transformation to the graphics // context so that this row paints in the right area. g.pushRegion(getExtent()); // Paint this manager's controlled fields. subpaint(g); g.setColor(0x00CACACA); g.drawLine(0, 0, getPreferredWidth(), 0); // Restore the graphics context. g.popContext(); } // Arrages this manager's controlled fields from left to right within // the enclosing table's columns. protected void sublayout(int width, int height) { // set the size and position of each field. int fontHeight = Font.getDefault().getHeight(); int preferredWidth = getPreferredWidth(); /* positioning of fields in list */ // Status Field field = getField(0); layoutChild(field, preferredWidth, 50); setPositionChild(field, 10, 5); // Name field = getField(1); layoutChild(field, 150, fontHeight + 1); //setPositionChild(field, 1, 2); setPositionChild(field, 80, fontHeight ); setExtent(preferredWidth, getPreferredHeight()); } // The preferred width of a row is defined by the list renderer. public int getPreferredWidth() { return Graphics.getScreenWidth(); } // The preferred height of a row is the "row height" as defined in the // enclosing list. public int getPreferredHeight() { return getRowHeight(); } } public Object get(ListField listField, int index) { return null; } public int getPreferredWidth(ListField listField) { return 0; } public int indexOfList(ListField listField, String prefix, int start) { return 0; } } FriendsRequestObject is given below - public class FriendsRequestObject { private String sender_id; private String sender_name; private String image; public FriendsRequestObject(String sender_id, String sender_name, String image){ this.sender_id = sender_id; this.sender_name =sender_name; this.image =image; } public String getimage() { return image; } public void setimage(String image) { this.image = image; } public String getSender_id() { return sender_id; } public void setSender_id(String sender_id) { this.sender_id = sender_id; } public String getSender_name() { return sender_name; } public void setSender_name(String sender_name) { this.sender_name = sender_name; } }
Edit your implementation of TableRowManager. You need to change the getPreferredWidth(), and getPreferredHeight(). getWidth() and getHeight() will return wrong value if the sublayout() method execution doesn't finish earlier. // The preferred width of a row is defined by the list renderer. public int getPreferredWidth() { return Display.getWidth(); } // The preferred height of a row is the "row height" as defined in the // enclosing list. public int getPreferredHeight() { return getRowHeight(); }
Blackberry: custom ButtonField with disappearing focus highlight
I'm trying to create a custom ButtonField, whose focus (the blue highlight color) would disappear after few seconds of inactivity - like in original music player on BB phones with touchscreen. I've almost succeeded in that with the following example: Here are the east.png and west.png (courtesy of openclipart.org): Here is my test code MyFocus.java: import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.decor.*; import net.rim.device.api.system.*; import net.rim.device.api.ui.image.*; public class MyFocus extends UiApplication { public static void main(String[] args) { MyFocus app = new MyFocus(); app.enterEventDispatcher(); } public MyFocus() { pushScreen(new MyScreen()); } } class MyScreen extends MainScreen { public MyScreen() { setTitle("2nd trackpad click not working"); getMainManager().setBackground(BackgroundFactory.createLinearGradientBackground(Color.WHITE, Color.GRAY, Color.DARKGRAY, Color.GRAY)); add(new MyButton(MyButton.EAST)); add(new MyButton(MyButton.WEST)); add(NF); } class MyButton extends ButtonField { public final static int EAST = 0; public final static int WEST = 1; public final static int WIDTH = 100; public final static int HEIGHT = 100; private final XYEdges EDGES = new XYEdges(0, 0, 0, 0); private final Application _app = UiApplication.getUiApplication(); private final static long FOCUS_DURATION = 3000L; private int _focusTimer = -1; private final int _direction; public MyButton(int direction) { setMargin(EDGES); setPadding(EDGES); setImageSize(WIDTH, HEIGHT); setBorder(VISUAL_STATE_NORMAL, BorderFactory.createSimpleBorder(EDGES)); setBorder(VISUAL_STATE_FOCUS, BorderFactory.createSimpleBorder(EDGES)); setBorder(VISUAL_STATE_ACTIVE, BorderFactory.createSimpleBorder(EDGES)); setBackground(VISUAL_STATE_NORMAL, BackgroundFactory.createSolidTransparentBackground(Color.GREEN, 0)); setBackground(VISUAL_STATE_FOCUS, BackgroundFactory.createSolidTransparentBackground(Color.BLUE, 100)); setBackground(VISUAL_STATE_ACTIVE, BackgroundFactory.createSolidTransparentBackground(Color.RED, 200)); _direction = direction; switch(_direction) { case EAST: setImage(ImageFactory.createImage("east.png")); break; case WEST: setImage(ImageFactory.createImage("west.png")); break; } } // display red background on long touch and hold protected boolean touchEvent(TouchEvent event) { if (event.getEvent() == TouchEvent.CLICK) { applyThemeOnStateChange(); return true; } return super.touchEvent(event); } protected void onUnfocus() { if (_focusTimer != -1) { _app.cancelInvokeLater(_focusTimer); _focusTimer = -1; } super.onUnfocus(); } protected void onFocus(int direction) { if (_focusTimer != -1) { _app.cancelInvokeLater(_focusTimer); _focusTimer = -1; } _focusTimer = _app.invokeLater(new Runnable() { public void run() { MyButton.super.onUnfocus(); _focusTimer = -1; } }, FOCUS_DURATION, false); super.onFocus(direction); } public int getPreferredHeight(){ return HEIGHT; } public int getPreferredWidth(){ return WIDTH; } protected void layout(int width, int height) { setExtent(WIDTH, HEIGHT); } } } My problem is visible, when I first select a button and wait few seconds for its focus to disappear. Then I click on the track pad and while the button is pushed (verified that), you don't see anything at the screen - it doesn't turn blue or red. I've tried all combinations of navigationClick() and trackwheelUnclick() but can not fix that. Any help please? Alex UPDATE 1: I've tried the following, but it doesn't work well (focus disappears forever, probably because button thinks it is in the needed visual state already): protected void onFocus(int direction) { if (_focusTimer != -1) { _app.cancelInvokeLater(_focusTimer); _focusTimer = -1; } _focusTimer = _app.invokeLater(new Runnable() { public void run() { MyButton.this.setBorder(BorderFactory.createSimpleBorder(EDGES)); MyButton.this.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.GREEN, 0)); invalidate(); _focusTimer = -1; } }, FOCUS_DURATION, false); super.onFocus(direction); } UPDATE 2: A try with a NullField, still not working properly: import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.decor.*; import net.rim.device.api.system.*; import net.rim.device.api.ui.image.*; public class MyFocus extends UiApplication { public static void main(String[] args) { MyFocus app = new MyFocus(); app.enterEventDispatcher(); } public MyFocus() { pushScreen(new MyScreen()); } } class MyScreen extends MainScreen { static NullField NF = new NullField(); HorizontalFieldManager hfm = new HorizontalFieldManager() { int lastFocused = -1; protected int firstFocus(int direction) { lastFocused = super.firstFocus(direction); System.out.println("XXX firstFocus: " + lastFocused); return lastFocused; } protected int nextFocus(final int direction, final int axis) { if (getFieldWithFocus() == NF) { return lastFocused; } lastFocused = super.nextFocus(direction, axis); System.out.println("XXX nextFocus: " + lastFocused); return lastFocused; } }; public MyScreen() { setTitle("2nd trackpad click not working"); getMainManager().setBackground(BackgroundFactory.createLinearGradientBackground(Color.WHITE, Color.GRAY, Color.DARKGRAY, Color.GRAY)); hfm.add(new MyButton(MyButton.WEST)); hfm.add(new MyButton(MyButton.EAST)); hfm.add(new MyButton(MyButton.EAST)); hfm.add(NF); add(hfm); } class MyButton extends ButtonField { public final static int EAST = 0; public final static int WEST = 1; public final static int WIDTH = 100; public final static int HEIGHT = 100; private final XYEdges EDGES = new XYEdges(0, 0, 0, 0); private final Application _app = UiApplication.getUiApplication(); private final static long FOCUS_DURATION = 3000L; private int _focusTimer = -1; private final int _direction; public MyButton(int direction) { setMargin(EDGES); setPadding(EDGES); setImageSize(WIDTH, HEIGHT); setBorder(VISUAL_STATE_NORMAL, BorderFactory.createSimpleBorder(EDGES)); setBorder(VISUAL_STATE_FOCUS, BorderFactory.createSimpleBorder(EDGES)); setBorder(VISUAL_STATE_ACTIVE, BorderFactory.createSimpleBorder(EDGES)); setBackground(VISUAL_STATE_NORMAL, BackgroundFactory.createSolidTransparentBackground(Color.GREEN, 0)); setBackground(VISUAL_STATE_FOCUS, BackgroundFactory.createSolidTransparentBackground(Color.BLUE, 100)); setBackground(VISUAL_STATE_ACTIVE, BackgroundFactory.createSolidTransparentBackground(Color.RED, 200)); _direction = direction; switch(_direction) { case EAST: setImage(ImageFactory.createImage("east.png")); break; case WEST: setImage(ImageFactory.createImage("west.png")); break; } } protected boolean touchEvent(TouchEvent event) { if (event.getEvent() == TouchEvent.CLICK) { applyThemeOnStateChange(); return true; } return super.touchEvent(event); } protected void onUnfocus() { if (_focusTimer != -1) { _app.cancelInvokeLater(_focusTimer); _focusTimer = -1; } super.onUnfocus(); } protected void onFocus(int direction) { if (_focusTimer != -1) { _app.cancelInvokeLater(_focusTimer); _focusTimer = -1; } _focusTimer = _app.invokeLater(new Runnable() { public void run() { MyScreen.NF.setFocus(); _focusTimer = -1; } }, FOCUS_DURATION, false); super.onFocus(direction); } public int getPreferredHeight(){ return HEIGHT; } public int getPreferredWidth(){ return WIDTH; } protected void layout(int width, int height) { setExtent(WIDTH, HEIGHT); } } }
I would probably ovverride the drawFocus() method to check a flag _showFocus before calling super.drawFocus(), then in onFocus(), set the flag to true and schedule the Runnable to change the _showFocus flag to false and invalidate (also setting it to false in onUnfocus()). Don't have to worry about canceling timers or anything this way either, as it is just going to change a flag and invalidate, keeping it in the appropriate state.
BasicEditField BlackBerry
I want a BasicEditField with rounded border and white background fill. This is my code public class BasicField extends BasicEditField { XYEdges padding = new XYEdges(0,0,0,0); int color = Color.BLACK; int lineStyle = Border.STYLE_SOLID; int Width, Height; Border roundedBorder = BorderFactory.createRoundedBorder(padding, color, lineStyle); public BasicField() { super(BasicEditField.NO_NEWLINE); //this.setPadding(2, 2, 2, 2); //this.setBorder(roundedBorder); } public int getPreferredWidth() { int labelWidth = getFont().getAdvance(getLabel()) - 1; Width = Graphics.getScreenWidth() -150; return Width; } public int getPreferredHeight() { return 10; } public void paint(Graphics g) { int currCol = g.getColor(); g.setBackgroundColor( Color.WHITE ); g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight() ); g.clear(); g.setColor( Color.NAVY ); super.paint( g ); } protected void layout( int maxWidth, int maxHeight ) { super.layout( getPreferredWidth(), getPreferredHeight() ); } }
Here you go - Screenshot: border.png: MyEdit.java: import net.rim.device.api.system.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.ui.decor.*; public class MyEdit extends UiApplication { public static void main(String args[]) { MyEdit app = new MyEdit(); app.enterEventDispatcher(); } public MyEdit() { pushScreen(new MyScreen()); } } class MyScreen extends MainScreen { Border myBorder = BorderFactory.createBitmapBorder( new XYEdges(20, 16, 27, 23), Bitmap.getBitmapResource("border.png")); BasicEditField myField = new BasicEditField(TextField.NO_NEWLINE) { protected void paint(Graphics g) { if (getTextLength() == 0) { g.setColor(Color.LIGHTGRAY); g.drawText("Search", 0, 0); } g.setColor(Color.BLACK); super.paint(g); } }; public MyScreen() { myField.setBorder(myBorder); setTitle(myField); } }
Friend... try this code..... class BasicEditScreen extends MainScreen { public BasicEditScreen() { add(new BasicField(200, 40, FIELD_LEFT, "Enter here..", "horizontal")); } } import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Font; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.EditField; import net.rim.device.api.ui.container.VerticalFieldManager; public class BasicField extends Manager { private int managerWidth; private int managerHeight; private int inactiveBorderColor = Color.GRAY; private int activeBorderColor = Color.GREENYELLOW; private int borderColor = inactiveBorderColor; private int backgroundColor = Color.WHITE; private int arcWidth; private VerticalFieldManager vfm ; private EditField editField; int nn =1; int count=0; public BasicField(int width, int height, long style, final String hint,String type_horizontal_vertical) { super(style | NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL); if(type_horizontal_vertical.equalsIgnoreCase("Horizontal")) vfm = new VerticalFieldManager(HORIZONTAL_SCROLL | USE_ALL_WIDTH ); if(type_horizontal_vertical.equalsIgnoreCase("Vertical")) vfm = new VerticalFieldManager(VERTICAL_SCROLL| USE_ALL_WIDTH | USE_ALL_HEIGHT); managerWidth = width; managerHeight = height; long innerStyle = style & (READONLY | FOCUSABLE_MASK); // at least if (innerStyle == 0) { innerStyle = FOCUSABLE; } if(style==EditField.FILTER_EMAIL) { innerStyle = EditField.FILTER_EMAIL; } if(style==EditField.FILTER_INTEGER) { innerStyle = EditField.FILTER_INTEGER; } editField = new EditField("", null, EditField.DEFAULT_MAXCHARS, innerStyle) { public void paint(Graphics g) { if(editField.getText().length()==0) { g.setColor(Color.GRAY); g.drawText(hint,5,2); super.paint(g); } g.setColor(Color.BLACK); super.paint(g); } }; arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE; // make it even add(vfm); vfm.add(editField); } public void setFont(Font font) { super.setFont(font); editField.setFont(font); arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE; updateLayout(); } public void setBorderColors(int inactive, int active) { inactiveBorderColor = inactive; activeBorderColor = active; invalidate(); } public void setBackgroundColor(int bgColor) { backgroundColor = Color.AQUA; invalidate(); } public String getText() { return editField.getText(); } public void setText(String newText) { editField.setText(newText); } public int getPreferredWidth() { return managerWidth; } public int getPreferredHeight() { return managerHeight; } protected void sublayout(int w, int h) { if (managerWidth == 0) { managerWidth = w; } if (managerHeight == 0) { managerHeight = h; } int actWidth = Math.min(managerWidth, w); int actHeight = Math.min(managerHeight, h); layoutChild(vfm, actWidth - arcWidth, actHeight - arcWidth); setPositionChild(vfm, arcWidth / 2, arcWidth / 2); setExtent(actWidth, actHeight); } protected void paint(Graphics g) { int prevColor = g.getColor(); int myWidth = managerWidth; int myHeight = managerHeight; g.setColor(backgroundColor); g.fillRoundRect(0, 0, myWidth, myHeight, arcWidth, arcWidth); g.setColor(borderColor); g.drawRoundRect(0, 0, myWidth, myHeight, 10,10); g.drawRoundRect(1, 1, myWidth - 2, myHeight - 2, 10-2, 10-2); g.setColor(prevColor); super.paint(g); } private void adjustBorderColor() { int nextColor; if (editField.isFocus()) { nextColor = activeBorderColor; } else { nextColor = inactiveBorderColor; } if (borderColor != nextColor) { borderColor = nextColor; invalidate(); } } }
Reduce height and width of BlackBerry BasicEditField
I am trying to change the width and height of a BlackBerry BasicEditField. But its not displaying the BasicEditField as i mention. HorizontalFieldManager HFMreg = new HorizontalFieldManager( HorizontalFieldManager.USE_ALL_WIDTH | HorizontalFieldManager.USE_ALL_HEIGHT) { //Override the paint method to draw the background image. public void paint(Graphics graphics) { //Draw the registration background image graphics.drawBitmap(0,0,Display.getWidth(),Display.getHeight(),BMregbg, 0, 0); super.paint(graphics); } }; BEFfirstname = new BasicEditField("","",5,EditField.NO_NEWLINE) { protected void paint(Graphics graphics) { graphics.fillRect(0,0,80,25); graphics.setBackgroundColor(Color.WHITE); graphics.clear(); super.paint(graphics); } protected void layout() { super.layout(getPreferredWidth(),getPreferredHeight()); setExtent(80,25); //width,height } public int getPreferredWidth() { int fieldWidth = 80; //required width return fieldWidth; } public int getPreferredHeight() { int fieldHeight = 25; // required height return fieldHeight; } }; //BEFfirstname.setMargin(200,0,0,60); HFMreg.add(LFfirstname); HFMreg.add(BEFfirstname); add(HFMreg);
just an other way round: BasicEditField BEFfirstname = new BasicEditField("","",5,EditField.NO_NEWLINE); MyManager obj = new MyManger(); obj.add(BEFfirstname); add(obj); class MyManager extends Manager { MyManager() { super(Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT); } protected void sublayout(int width, int height) { Field f = getField(0); layoutChild(f,80,25); setPositionChild(f, 10, 10); } }
Blackberry - how to animate Custom Field?
I have created a custom field class "Seek" to draw a fillrectangle. class Seek extends Field { int fill; protected void layout(int width, int height) { setExtent(320, 5); } protected void paint(Graphics graphics) { graphics.setColor(Color.RED); graphics.fillRect(0, 0, fill, 5); } protected void setValue(int value) { fill = value; } } And I have created another class Test seek to set the fill value using a timer public class TestSeek extends UiApplication { public static void main(String[] args) { TestSeek gbResults = new TestSeek(); gbResults.enterEventDispatcher(); } private TestSeek() { pushScreen(new ProgressScreen()); } } class ProgressScreen extends MainScreen { Timer timer = new Timer(); int i = 80; Seek SeekField = new Seek(); public ProgressScreen() { add(SeekField); timer.schedule(new RemindTask(), 100, 10); } class RemindTask extends TimerTask { public void run() { if (i < 320) { i += 1; SeekField.setValue(i); } else timer.cancel(); } } } But I am unable to animate filling the rectangle.
Try calling invalidate() in your setValue method.