Windows 8 WWW porting issue - windows

Trying to port a game, I'm having trouble making a high score board for a unity app for the windows 8 app store. The issue is that it never returns the results. I ran fiddler and can't see the game generating any packets.
using UnityEngine;
using System.Collections;
using System.Text;
using System.Security;
public class Highscore : MonoBehaviour
{
public string secretKey = "12345";
public string PostScoreUrl = "http://YouWebsite.com/.../postScore.php?";
public string GetHighscoreUrl = "http://YouWebsite.com/.../getHighscore.php";
private string name = "Name";
private string score = "Score";
private string WindowTitel = "";
private string Score = "";
public GUISkin Skin;
public float windowWidth = 400;
private float windowHeight = 250;
public Rect windowRect;
public int maxNameLength = 10;
public int getLimitScore = 15;
void Start ()
{
windowRect = new Rect (120, 40, 300, 300);
StartCoroutine("GetScore");
}
void Update ()
{
windowRect = new Rect (Screen.width / 3 , Screen.width / 6,Screen.width / 3,Screen.width / 3);
windowHeight = Screen.height - 50;
}
IEnumerator GetScore()
{
Score = "";
WindowTitel = "Loading";
WWWForm form = new WWWForm();
form.AddField("limit",getLimitScore);
WWW www = new WWW(GetHighscoreUrl,form);
yield return www;
if(www.text == "")
{
print("There was an error getting the high score: " + www.error);
WindowTitel = "There was an error getting the high score";
}
else
{
WindowTitel = "Highscore Board";
Debug.Log (www);
Score = www.text;
}
}
IEnumerator PostScore(string name, int score)
{
string _name = name;
int _score = score;
if (_name != "Name"){
string hash = Md5Sum(_name + _score + secretKey).ToLower();
WWWForm form = new WWWForm();
form.AddField("name",_name);
form.AddField("score",_score);
form.AddField("hash",hash);
WWW www = new WWW(PostScoreUrl,form);
WindowTitel = "Wait";
yield return www;
if(www.text == "done")
{
StartCoroutine("GetScore");
PlayerPrefs.SetFloat("currentScore", 0);
}
else
{
print("There was an error posting the high score: " + www.error);
WindowTitel = "There was an error posting the high score";
}
} else { WindowTitel = "Enter your name before posting a high score"; }
}
void OnGUI()
{
GUI.skin = Skin;
windowRect = GUI.Window(0, windowRect, DoMyWindow, WindowTitel);
name = GUI.TextField (new Rect (Screen.width / 2 - Screen.height / 10 - Screen.height / 5, Screen.height / 3 - Screen.height / 7, Screen.height / 5, Screen.height / 15), name, maxNameLength);
score = PlayerPrefs.GetFloat("currentScore").ToString();
if (GUI.Button(new Rect(Screen.width / 2 - Screen.width / 30 + Screen.width / 20, Screen.height / 3 - Screen.height / 7, Screen.height / 5 + 50, Screen.height / 15),"Post Score"))
{
StartCoroutine(PostScore(name, int.Parse(score)));
name = "";
score = "";
}
}
void DoMyWindow(int windowID)
{
GUI.skin = Skin;
GUI.Label (new Rect (windowWidth / 2 + windowWidth / 15 + windowWidth / 15 + windowWidth / 25, windowHeight / 15 , windowWidth, windowHeight), Score);
}
public string Md5Sum(string input)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hash = UnityEngine.Windows.Crypto.ComputeMD5Hash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}

Related

how do i make FlxAsyncLoop work for making a progress bar in HaxeFlixel?

so, i tried to make an async loop for my game (to make a progress bar) and the game crashes when the state loads...
i tried to change the loops position so they don't collide and all of the code is from the FlxAsyncLoop demo but with other variables and some other changes.
here's the code:
import flixel.FlxCamera;
import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.addons.util.FlxAsyncLoop;
import flixel.group.FlxGroup;
import flixel.math.FlxPoint;
import flixel.math.FlxVelocity;
import flixel.text.FlxText;
import flixel.ui.FlxBar;
import flixel.util.FlxColor;
class PlayState extends FlxState
{
public static var player:FlxSprite;
var ground:FlxSprite;
var axe:FlxSprite;
var wood:FlxSprite;
var base:FlxSprite;
var txt:FlxText;
var playerPos:FlxPoint;
var enemy:FlxSprite;
var move = false;
var progressR:FlxGroup;
var progressE:FlxGroup;
var resourceGroup:FlxGroup;
var enemyGroup:FlxGroup;
var maxItems:Int = 100;
var bar1:FlxBar;
var bartxt1:FlxText;
var bar2:FlxBar;
var bartxt2:FlxText;
var loopR:FlxAsyncLoop;
var loopE:FlxAsyncLoop;
public function addR()
{
var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
wood.makeGraphic(40, 100, FlxColor.BROWN);
add(wood);
bar1.value = (resourceGroup.members.length / maxItems) * 100;
bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
bartxt1.screenCenter();
}
public function addE()
{
var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
enemy.makeGraphic(32, 32, FlxColor.RED);
add(enemy);
bar2.value = (enemyGroup.members.length / maxItems) * 100;
bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
bartxt2.screenCenter();
}
override public function create()
{
super.create();
resourceGroup = new FlxGroup(maxItems);
enemyGroup = new FlxGroup(maxItems);
loopR = new FlxAsyncLoop(maxItems, addR);
loopE = new FlxAsyncLoop(maxItems, addE);
FlxG.camera.zoom = 0.5;
playerPos = FlxPoint.get();
ground = new FlxSprite(0, 0);
ground.makeGraphic(2500, 1800, FlxColor.GREEN);
add(ground);
player = new FlxSprite(100, 100);
player.loadGraphic(AssetPaths.n1__png);
axe = new FlxSprite(player.x + 60, player.y);
axe.loadGraphic(AssetPaths.axeR__png);
camera = new FlxCamera(0, 0, 2500, 1800);
camera.bgColor = FlxColor.TRANSPARENT;
camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
FlxG.cameras.reset(camera);
camera.target = player;
if (FlxG.collide(wood, player))
FlxObject.separate(wood, player);
if (FlxG.collide(wood, enemy))
FlxObject.separate(wood, enemy);
if (FlxG.collide(enemy, player))
FlxObject.separate(enemy, player);
progressR = new FlxGroup();
bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
bar1.value = 0;
bar1.screenCenter();
progressR.add(bar1);
bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
bartxt1.screenCenter();
progressR.add(bartxt1);
progressE = new FlxGroup();
bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
bar2.value = 0;
bar2.screenCenter();
progressE.add(bar2);
bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
bartxt2.screenCenter();
progressE.add(bartxt2);
resourceGroup.visible = false;
resourceGroup.active = false;
enemyGroup.visible = false;
enemyGroup.active = false;
add(progressR);
add(progressE);
add(resourceGroup);
add(enemyGroup);
add(loopR);
}
override public function update(elapsed:Float)
{
super.update(elapsed);
if (FlxG.keys.pressed.LEFT && move)
{
player.x -= 5;
axe.loadGraphic(AssetPaths.axeL__png);
}
if (FlxG.keys.pressed.RIGHT && move)
{
player.x += 5;
axe.loadGraphic(AssetPaths.axeR__png);
}
if (FlxG.keys.pressed.UP && move)
{
player.y -= 5;
}
if (FlxG.keys.pressed.DOWN && move)
{
player.y += 5;
}
axe.x = player.x + 60;
axe.y = player.y;
playerPos = FlxPoint.get();
playerPos = player.getMidpoint();
FlxVelocity.moveTowardsPoint(enemy, playerPos, 70);
if (!loopR.started)
{
loopR.start();
}
else
{
if (loopR.finished)
{
resourceGroup.visible = true;
progressR.visible = false;
resourceGroup.active = true;
progressR.active = false;
loopR.kill();
loopR.destroy();
add(loopE);
loopE.start();
}
}
if (loopE.finished)
{
move = true;
add(player);
add(axe);
enemyGroup.visible = true;
progressE.visible = false;
enemyGroup.active = true;
progressE.active = false;
loopE.kill();
loopE.destroy();
}
}
}
i'm showing everything because of the functions and other things that can make this problem
(my english is bad sorry if i miss something...)
Without knowing the exact error, I suspect that the problem is when you call
if (FlxG.collide(wood, player))
FlxObject.separate(wood, player);
if (FlxG.collide(wood, enemy))
FlxObject.separate(wood, enemy);
if (FlxG.collide(enemy, player))
FlxObject.separate(enemy, player);
Inside your create function - wood and enemy are declared in other functions and do not exist there.
There are a couple of things I would do differently here:
(Note: I didn't TEST this code, so there may still be problems, but this might help get you pointed in the right direction...)
class PlayState extends FlxState
{
public static var player:FlxSprite;
var ground:FlxSprite;
var axe:FlxSprite;
var base:FlxSprite;
var txt:FlxText;
var playerPos:FlxPoint;
var move:Bool = false;
var progressR:FlxGroup;
var progressE:FlxGroup;
var resourceGroup:FlxTypedGroup<FlxSprite>;
var enemyGroup:FlxTypedGroup<FlxSprite>;
var maxItems:Int = 100;
var bar1:FlxBar;
var bartxt1:FlxText;
var bar2:FlxBar;
var bartxt2:FlxText;
var loopR:FlxAsyncLoop;
var loopE:FlxAsyncLoop;
public function addR()
{
var wood = new FlxSprite(FlxG.random.int(100, 2500), FlxG.random.int(100, 1800));
wood.makeGraphic(40, 100, FlxColor.BROWN);
resourceGroup.add(wood);
bar1.value = (resourceGroup.members.length / maxItems) * 100;
bartxt1.text = "Loading resources... " + resourceGroup.members.length + " / " + maxItems;
bartxt1.screenCenter();
FlxG.collide(player, resourceGroup) // should not need to call `seperate` - it's automatic when using `collide` vs `overlap`
}
public function addE()
{
var enemy = new FlxSprite(FlxG.random.int(300, 2500), FlxG.random.int(300, 1800));
enemy.makeGraphic(32, 32, FlxColor.RED);
enemyGroup.add(enemy);
FlxG.collide(enemyGroup, resourceGroup)
FlxG.collide(player, resourceGroup)
bar2.value = (enemyGroup.members.length / maxItems) * 100;
bartxt2.text = "Loading enemys... " + enemyGroup.members.length + " / " + maxItems;
bartxt2.screenCenter();
}
override public function create()
{
super.create();
resourceGroup = new FlxTypedGroup<FlxSprite>(maxItems);
enemyGroup = new FlxTypedGroup<FlxSprite>(maxItems);
loopR = new FlxAsyncLoop(maxItems, addR);
loopE = new FlxAsyncLoop(maxItems, addE);
FlxG.camera.zoom = 0.5;
playerPos = FlxPoint.get();
ground = new FlxSprite(0, 0);
ground.makeGraphic(2500, 1800, FlxColor.GREEN);
add(ground);
player = new FlxSprite(100, 100);
player.loadGraphic(AssetPaths.n1__png);
axe = new FlxSprite(player.x + 60, player.y);
axe.loadGraphic(AssetPaths.axeR__png);
camera = new FlxCamera(0, 0, 2500, 1800);
camera.bgColor = FlxColor.TRANSPARENT;
camera.setScrollBoundsRect(0, 0, ground.width, ground.height);
FlxG.cameras.reset(camera);
camera.target = player;
progressR = new FlxGroup();
bar1 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
bar1.value = 0;
bar1.screenCenter();
progressR.add(bar1);
bartxt1 = new FlxText(0, 0, FlxG.width, "Loading resources... 0 / " + maxItems);
bartxt1.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
bartxt1.screenCenter();
progressR.add(bartxt1);
progressE = new FlxGroup();
bar2 = new FlxBar(0, 0, LEFT_TO_RIGHT, FlxG.width, 50, null, "", 0, 100, true);
bar2.value = 0;
bar2.screenCenter();
progressE.add(bar2);
bartxt2 = new FlxText(0, 0, FlxG.width, "Loading enemys... 0 / " + maxItems);
bartxt2.setFormat(null, 28, FlxColor.WHITE, CENTER, OUTLINE);
bartxt2.screenCenter();
progressE.add(bartxt2);
resourceGroup.visible = false;
resourceGroup.active = false;
enemyGroup.visible = false;
enemyGroup.active = false;
add(progressR);
add(progressE);
add(resourceGroup);
add(enemyGroup);
add(loopR);
}
public function gamePlay(elapsed:Float):Void
{
if (FlxG.keys.pressed.LEFT && move)
{
player.x -= 5; // why +/- position and not .velocity?
// THIS is probably not right - you want to use a sprite sheet with animations and call axe.play("left") or something...
axe.loadGraphic(AssetPaths.axeL__png);
}
if (FlxG.keys.pressed.RIGHT && move)
{
player.x += 5;
axe.loadGraphic(AssetPaths.axeR__png);
}
if (FlxG.keys.pressed.UP && move)
{
player.y -= 5;
}
if (FlxG.keys.pressed.DOWN && move)
{
player.y += 5;
}
axe.x = player.x + 60;
axe.y = player.y;
playerPos = FlxPoint.get();
playerPos = player.getMidpoint();
for (e in enemyGroup)
{
FlxVelocity.moveTowardsPoint(e, playerPos, 70);
}
}
public function loading(elapsed:Float):Void
{
if (!loopR.started)
{
loopR.start();
}
else if (loopR.finished)
{
resourceGroup.visible = true;
progressR.visible = false;
resourceGroup.active = true;
progressR.active = false;
loopR.kill();
loopR.destroy();
add(loopE);
loopE.start();
}
else if (loopE.finished)
{
move = true;
add(player);
add(axe);
enemyGroup.visible = true;
progressE.visible = false;
enemyGroup.active = true;
progressE.active = false;
loopE.kill();
loopE.destroy();
}
}
override public function update(elapsed:Float)
{
super.update(elapsed);
if (!move)
{
loading(elapsed);
}
else
{
gamePlay(elapsed);
}
}
}

How to draw speedometer or circular chart using xamarin forms

Recently, I started development using Xamarin.Forms in Visual Studio.
I need to draw something like this:
Is it possible using xamarin forms or is there any sample code for reference?
Thanks
I would look at the Syncfusion Circular Guage
See images below:
I am not 100% sure on the licencing, but I think they provide a Community Licence
Sorry for my English.
I have made something like that, see the picture below.
I copied some codes from some forums and made some ajusts of my own. But the principle is there, maybe adjust a few things and you can manage to achieve what you want. The adjusts that I made don't respect the proportional size in xaml (widht, height), I used the Request = 200. I hope that it can help you.
using System;
using System.Collections.Generic;
using System.Text;
using Microcharts.Forms;
using Microcharts;
using SkiaSharp;
using System.Linq;
namespace MES_App1.Chart
{
class SpeedometerChart : RadialGaugeChart
{
public SpeedometerChart()
{
BackgroundColor = SKColors.White;
}
private const float startAngle = 150;
private const float backgroundSweepAngle = 240;
public override void DrawContent(SKCanvas canvas, int width, int height)
{
var diferenceX = width > height ? (width - height) / 2 : 0;
var diferenceY = height > width ? (height - width) / 2 : 0;
var strokeWidth = (4 * (width - diferenceX)) / 100;
var rect = new SKRect(
5 + strokeWidth + diferenceX,
5 + strokeWidth + diferenceY + 50,
width - (5 + strokeWidth + diferenceX),
height - (5 + strokeWidth + diferenceY)+50);
var paint = new SKPaint
{
Style = SKPaintStyle.Stroke,
Color = SKColor.Parse("#008000"),
StrokeWidth = strokeWidth*4,
IsAntialias = true,
IsStroke = true
};
float[] angulos = { 1, 0.85f, 0.7f, 0.55f, 0.4f, .25f };
string[] angulosStr = { "100%", "85%", "70%", "55%", "40%", "25%" };
string[] cores = { "#008000", "#32CD32", "#5F9EA0", "#FFA500", "#FFD700", "#FF0000" };
for (int i = 0; i < angulos.Length; i++)
{
using (SKPath backgroundPath = new SKPath())
{
paint.Color = SKColor.Parse(cores[i]);
backgroundPath.AddArc(rect, startAngle, backgroundSweepAngle * angulos[i]);
canvas.DrawPath(backgroundPath, paint);
}
using (SKPath labelPath = new SKPath())
{
var rectLabels = new SKRect
{
Left=rect.Left-strokeWidth*2-20,
Top=rect.Top-strokeWidth*2-20,
Right=rect.Right+strokeWidth*2+20,
Bottom=rect.Bottom+strokeWidth*2+20
};
var labelPaint = new SKPaint
{
Style = SKPaintStyle.Stroke,
BlendMode = SKBlendMode.Clear,
Color = SKColors.Black,
StrokeWidth = 0,
IsAntialias = true,
IsStroke = true
};
labelPath.AddArc(rectLabels, startAngle, backgroundSweepAngle * angulos[i]);
canvas.DrawPath(labelPath, labelPaint);
canvas.DrawCaptionLabels(string.Empty, SKColor.Empty, angulosStr[i], SKColors.Black, 20,labelPath.LastPoint, SKTextAlign.Center);
}
}
float[] angulosLabel = { 1f, 0.85f, 0.7f, 0.55f, .25f };
float[] offsetLabels = { 20, 25, 20, 30, 30};
string[] labelsStr = { "Ideal", "Alta", "Tipico", "Precisa Melhoria", "Inaceitavel" };
for (int i = angulosLabel.Length-1; i >= 0; i--)
{
float anguloInicial;
if (i == angulosLabel.Length-1)
{
anguloInicial = startAngle;
}
else
{
anguloInicial = startAngle+backgroundSweepAngle * angulosLabel[i + 1];
}
using (SKPath labelPath = new SKPath())
{
var labelPaint = new SKPaint
{
TextSize=18
};
labelPath.AddArc(rect, anguloInicial, backgroundSweepAngle * angulosLabel[i]);
canvas.DrawTextOnPath(labelsStr[i], labelPath, offsetLabels[i], -10, labelPaint);
if (labelsStr[i] == "Alta")
{
labelPaint.TextSize = 16;
canvas.DrawTextOnPath("Performance", labelPath, 0, 10, labelPaint);
}
}
}
using (SKPath circlePath = new SKPath())
{
var circlePaint = new SKPaint
{
Style = SKPaintStyle.Fill,
Color = SKColors.Black,
IsAntialias = true
};
circlePath.AddCircle(rect.MidX, rect.MidY, 20);
canvas.DrawPath(circlePath, circlePaint);
}
foreach (var entry in Entries.OrderByDescending(e => e.Value))
{
using (SKPath pointerPath = new SKPath())
{
var colors = new[]
{
SKColors.SlateGray,
SKColors.Gray,
SKColors.Black
};
var shader = SKShader.CreateLinearGradient(
new SKPoint(128.0f, 0.0f),
new SKPoint(128.0f,256.0f),
colors,
null,
SKShaderTileMode.Clamp);
var labelPaint = new SKPaint
{
Style = SKPaintStyle.Fill,
StrokeJoin = SKStrokeJoin.Miter,
Shader = shader,
IsAntialias = true
};
canvas.Save();
canvas.RotateDegrees(entry.Value/100*backgroundSweepAngle-120, rect.MidX, rect.MidY);
pointerPath.MoveTo(rect.MidX-10, rect.MidY);
pointerPath.LineTo(rect.MidX, rect.Top);
canvas.DrawCaptionLabels(string.Empty, SKColor.Empty, entry.Value.ToString() + "%", SKColors.Black, 20, pointerPath.LastPoint, SKTextAlign.Center);
pointerPath.LineTo(10+rect.MidX, rect.MidY);
pointerPath.Close();
canvas.DrawPath(pointerPath, labelPaint);
canvas.Restore();
}
}
}
}
}

How to create an event handler for objects in array?

I'm making a game in which an ellipse is created whenever random number generated is 6. But all of these objects are in an array. Whenever last object of ellipse is created then event handler only works for it and not for previous objects . I've used sender argument to recognize the source but it gives and exception . Here's my code
public static Ellipse[] greenEllipse = new Ellipse[10];
Game.green++;
Game.greenEllipse[green] = new Ellipse();
SolidColorBrush s = new SolidColorBrush();
s.Color = Colors.Green;
SolidColorBrush blackBrush = new SolidColorBrush();
blackBrush.Color = Colors.Black;
// Set Ellipse's width and color
greenEllipse[green].StrokeThickness = 2;
greenEllipse[green].Stroke = blackBrush;
// Fill rectangle with blue color
greenEllipse[green].Fill = s;
greenEllipse[green].Height = 40;
greenEllipse[green].Width = 45;
greenEllipse[green].RenderTransform = new TranslateTransform { X = -200, Y = -72 };
greenEllipse[green].PointerPressed += OnClickge;
g.Children.Add(greenEllipse[green]);
private void OnClickge(object sender, RoutedEventArgs e)
{
var ocg = sender;
tt.Text = nee.ToString();
if (green1 < 4 && nee != 5 && nee != 6)
{
Game.px += nee * 40;
Game.greenEllipse[Convert.ToInt32(ocg)].RenderTransform = new TranslateTransform { X = px, Y = py };
green1 += nee;
}
if (nee == 5)
{
Game.py += (nee) * (-20);
Game.greenEllipse[Convert.ToInt32(ocg)].RenderTransform = new TranslateTransform { X = px + nee, Y = py };
}
if (green1 > 4)
{
if (nee != 5)
{
green1--;
Game.py += nee * (-20);
Game.greenEllipse[Convert.ToInt32(ocg)].RenderTransform = new TranslateTransform { X = px + nee, Y = py };
}
}
}

Binding Scene size properties to Stage JavaFX

I need to adjust the size of a Scene to the current size of the Stage/Window.
Currently when I resize the Stage/Window the Scene resizes as well, but not to the same size. The Scene contains a StackPane.
I looked for a way to bind but didn't find anything, setters for the size parameters of the Scene also aren't available it seems. Does anyone know a way to get this done?
EDIT: Here's the Code of my Class atm.
public class SimpleSun extends Application {
// Controls
Label lblPos = new Label();
Stage primaryStage;
List<Visibility> vislist;
Scene scene;
Rectangle rect;
Circle circle;
Line line1;
Line line2;
// Variables
private double sunDiameter = 700;
private Integer center = 400;
int fovrad = 80;
int fovpxl = calculatePixelsFromRad(fovrad);
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("static-access")
#Override
public void start(final Stage stage) {
// Initialize Containers
this.primaryStage = stage;
primaryStage.setTitle("0.1-alpha -- Sun Simulation");
BorderPane root = new BorderPane();
scene = new Scene(root, 800, 800);
StackPane sp = new StackPane();
// Paint Graphics
rect = new Rectangle(center - fovpxl / 2, center - fovpxl / 2, fovpxl,
fovpxl);
circle = new Circle(400, 400, 350);
line1 = new Line(0, 0, 0, scene.getHeight());
line2 = new Line(0, 0, scene.getHeight(), 0);
// Insert Controls
sp.getChildren().addAll(circle, line1, line2, lblPos, rect);
sp.setAlignment(lblPos, Pos.TOP_LEFT);
lblPos.setStyle("margin-top:10px");
root.setCenter(sp);
primaryStage.setScene(scene);
// Binding Circle size to stage & Scene size to Stage
circle.radiusProperty().bind(
primaryStage.widthProperty().divide(2).subtract(50));
circle.centerXProperty().bind(primaryStage.widthProperty().divide(2));
circle.centerYProperty().bind(primaryStage.widthProperty().divide(2));
// Assign Handlers
line1.setOnMouseClicked(mouseHandler);
line1.setOnMouseMoved(mouseHandler);
line2.setOnMouseClicked(mouseHandler);
line2.setOnMouseMoved(mouseHandler);
circle.setOnMouseClicked(mouseHandler);
circle.setOnMouseMoved(mouseHandler);
rect.setOnMouseClicked(mouseHandler);
rect.setOnMouseMoved(mouseHandler);
scene.widthProperty().addListener(cListener);
scene.heightProperty().addListener(cListener);
// Properties
circle.setFill(Color.YELLOW);
circle.setStroke(Color.BLACK);
rect.setFill(null);
rect.setStroke(Color.BLACK);
primaryStage.show();
}
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_CLICKED) {
int x = (int) mouseEvent.getSceneX();
int y = (int) mouseEvent.getSceneY();
DoubleMatrix1D pCoords = calculateXYRad(x, y);
final ISource p = new GaussianRadialSource(pCoords.get(0),
pCoords.get(1), 1, 1, 0);
MainSimulation.runSim(p, fovrad);
// DEBUG
// String message = "Source Position: " + mouseEvent.getSceneX()
// + " / " + mouseEvent.getSceneY();
// System.out.println(message);
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_MOVED) {
int x = (int) mouseEvent.getSceneX();
int y = (int) mouseEvent.getSceneY();
if (mouseEvent.getSource().getClass().equals(Circle.class)) {
((Circle) mouseEvent.getSource())
.setCursor(Cursor.CROSSHAIR);
} else if (mouseEvent.getSource().getClass().equals(Line.class)) {
((Line) mouseEvent.getSource()).setCursor(Cursor.CROSSHAIR);
} else if (mouseEvent.getSource().getClass()
.equals(Rectangle.class)) {
((Rectangle) mouseEvent.getSource())
.setCursor(Cursor.CROSSHAIR);
}
DoubleMatrix1D pCoords = calculateXYRad(x, y);
// Adjust label to new cursor position
lblPos.setText((pCoords.get(0) + " :: " + pCoords.get(1)));
// DEBUG
System.out.println("x: " + pCoords.get(0) + ", y: "
+ pCoords.get(1));
}
}
};
ChangeListener<? super Number> cListener = new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> scenewidth,
Number oldValue, Number newValue) {
// System.out.println(primaryStage.getHeight());
// Adjust Size of Window instead of binding
if (primaryStage.getHeight() < primaryStage.getWidth()) {
primaryStage.setWidth(primaryStage.getHeight());
center = (int) (primaryStage.getHeight() / 2);
sunDiameter = primaryStage.getHeight() - 100;
}
if (primaryStage.getWidth() < primaryStage.getHeight()) {
primaryStage.setHeight(primaryStage.getWidth());
center = (int) (primaryStage.getWidth() / 2);
sunDiameter = primaryStage.getWidth() - 100;
}
// Adjust Center and Sun Diameter to new Window Size
repaintSimpleSun();
System.out.println(primaryStage.getWidth() + " " + primaryStage.getHeight());
System.out.println(scene.getWidth() + " " + scene.getHeight());
System.out.println(center + " " + sunDiameter);
}
};
private DoubleMatrix1D calculateXYRad(int x, int y) {
double X = ((x - center) * (Units.SUN_HALF_DIAMETER_RAD * 2.0) / sunDiameter);
double Y = ((y - center) * (Units.SUN_HALF_DIAMETER_RAD * 2.0) / sunDiameter);
return DoubleFactory1D.dense.make(new double[] { X, Y });
}
private int calculatePixelsFromRad(int rad) {
int pixels = (int) ((sunDiameter) / (Units.SUN_HALF_DIAMETER_RAD * 2) * rad);
// System.out.println(pixels);
return pixels;
}
private void repaintSimpleSun() {
fovpxl = calculatePixelsFromRad(fovrad);
rect.setHeight(fovpxl);
rect.setWidth(fovpxl);
rect.setX(center - (fovpxl / 2));
rect.setY(center - (fovpxl / 2));
line1.setEndY(primaryStage.getWidth());
line2.setEndX(primaryStage.getHeight());
}
}

Blackberry APplication not rendering well on PORSCHE phones

I have got a Blackberry native application I have been working on in the past few weeks.
Basically it consists of a few screens in which I get to draw the designs of my screen by overriding the paint method of the FieldManagers
I have tested on blackberry 4.5 and other blackberry's.
It has rendered well so far until I ran into a hitch testing on Blackberry's Porsche version
which does not render my designs well. What I experience is that on scrolling, my screen gets wiped off.
Pls does any one here experienced such issues in the past and what would be the cause. I would be willing to show sections of the code to give insight into the issues I am experiencing. Least I mention it displays well on the simulator without these issues.
I have posted a sample screen which is my login screen:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
final VerticalFieldManager spaceHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new Util().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),topSpaceHeight);
setExtent(Display.getWidth(), topSpaceHeight);
}
};
final VerticalFieldManager contentHolderPix = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
System.out.println(">>>>!!!!>>>>" + "img/icons/logo" + new Util().getResource() + ".png");
EncodedImage image_1 = EncodedImage.getEncodedImageResource("img/icons/icon" + new Util().getResource() + ".png");
setFont(util.initializeUtilFont("Arial", editFieldFontHeaderSize, Font.BOLD));
int startHere = topSpaceHeight - image_1.getHeight() - 5;
int imageWidth1 = (int)((Display.getWidth() - image_1.getWidth() - getFont().getAdvance("Sign In"))/2);
graphics.drawBitmap(new XYRect(imageWidth1 - 10 - whiteBgEdge.left - whiteBgEdge.right, startHere, image_1.getWidth(), image_1.getHeight()), image_1.getBitmap(), 0, 0);
int startfonty = startHere + ((image_1.getHeight() - getFont().getHeight())/2);
graphics.drawText("Sign In", imageWidth1, startfonty);
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(whiteBgWidth,topSpaceHeight);
setExtent(whiteBgWidth, topSpaceHeight);
setMargin(whiteBgEdge);
}
};
System.out.println("whiteBgWidth>>>>" + whiteBgWidth);
System.out.println("padExtWhiteBg>>>>" + padExtWhiteBg);
usernameField = utilNew.newEditTextField(editFieldWidth, editFont.getHeight(), 30,
EditField.NO_NEWLINE, "", editFieldPad, editFont, false, "Username");
passwordField = utilNew.newPasswordField(editFieldWidth, editFont.getHeight(), 30,
PasswordEditField.NO_NEWLINE, "Password", editFieldPad, editFont);
//usernameField.setMargin(holderPad1);
if(user_!=null && user_.getSignInUserName()!=null && user_.getSignInUserName().trim().length()>0)
usernameField.setText(user_.getSignInUserName());
final int edHt = editFont.getHeight() + editFieldPad.top + editFieldPad.bottom;
final int edWt = editFieldWidth + editFieldPad.left + editFieldPad.right;
System.out.println("edHt = " + edHt);
System.out.println("edWt = " + edWt);
System.out.println("HolderPad1 = " + holderPad1.top + ", " + holderPad1.bottom + ", " + holderPad1.left + ", " + holderPad1.right);
usernameFieldHolder = utilNew.generateEditTextField(usernameField, true, holderPad1, edHt, edWt, true);
passwordFieldHolder = utilNew.generateEditTextField(passwordField, true, holderPad2, edHt, edWt, false);
final int height_ = edHt + edHt + holderPad1.top + holderPad1.bottom + holderPad2.top + holderPad2.bottom + 20;
System.out.println("height___>>>>>" + height_);
final VerticalFieldManager contentHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
//System.out.println(edHt + "," + edHt + "," + holderPad1.top + "," + holderPad1.bottom + "," + holderPad2.top + "," + holderPad2.bottom);
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
graphics.drawRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.fillRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.setColor(0x00808080);
//System.out.println("This is changed?");
//System.out.println("<<<<<<.." + usernameFieldHolder.getPreferredHeight() + "hfm.getPreferredHeight() = 0" + usernameFieldHolder.getWidth() );
//graphics.drawLine(40, usernameField.getPreferredHeight(), whiteBgWidth, usernameField.getPreferredHeight());/**/
super.paint(graphics);
}
public void sublayout(int width, int height){
System.out.println(Display.getHeight() + " - " + Display.getWidth());
System.out.println("Wdith & height = " + width + " && " + height);
System.out.println("Wdith & this.getPreferredHeight() = " + this.getWidth() + " && " + this.getHeight());
super.sublayout(whiteBgWidth,height_);
setExtent(whiteBgWidth, height_);
setMargin(whiteBgEdge);
}
};
int buttonHeight = 70;
/*CustomManager hfm_buttons = util.generateHFM1(
contentHolder1.getPreferredWidth(),
buttonHeight,
new Util().whitebrand,
0);*/
//submitButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "LOGIN", null);
//registerButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "REGISTER", null);
final LabelField loginButton = new LabelField("", Field.FOCUSABLE)
{
private int hColor;
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth())+2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Sign In"))/2;
g.drawText("Sign In", width, height);
setExtent(totalWidth+ 5,left.getHeight() + 10);
//setMargin(new XYEdges(20, 10, 0, whiteBgEdge.left));
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
String userName = usernameField.getText().toString().toLowerCase();
user_.setSignInUserName(userName);
String passWord = passwordField.getText().toString();
System.out.println("username = " + userName + " & password = " + passWord);
User user = User.getInstance();
System.out.println(">>instance of user from sign in: " + user);
Records record = new Records();
if(passWord.trim().length() < 2 || userName.trim().length() < 2){
Dialog.alert("Invalid username and/or password entered");
SignIn screen = new SignIn();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(screen);
}else{
System.out.println("else if data is calid");
String hashPassword = user.md5Java(passWord);
hashPassword = "e86e107b113b0f830b9b817b4a9addb8";
user_.setUserName(userName);
user_.setPassword(passWord);
System.out.println("Check data availability");
try
{
FileConnection fc = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION);
FileConnection fc1 = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION_REF);
if (!fc.exists())
{
fc.mkdir();
if (!fc1.exists())
{
fc.mkdir();
}
}
fc.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage() );
}
if((record.isDataAvailable(record.userTable)==true))
{
System.out.println(">>>>### -1 ");
String[] allRecords = record.getAllRecords(record.userTable);
boolean proceedYes = true;
int count = 0;
while(proceedYes && count<allRecords.length)
{
System.out.println(">>>> Record = " + allRecords[count]);
//Dialog.alert(">>>> Record = " + allRecords[count]);
DataInputStream is = new DataInputStream(new ByteArrayInputStream(allRecords[count].getBytes()));
try {
System.out.println(">>>>555");
//System.out.println(">>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
String l = is.readUTF();
String u = is.readUTF();
String p = is.readUTF();
//System.out.println("e>>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
System.out.println("f>>>>" + l + " && " + u + " && " + p);
System.out.println("g>>>>" + userName + " && " + passWord + " && " + p);
if(u.equals(userName) && p.equals(passWord))
{
//Dialog.alert(">>>>12");
System.out.println(">>>889948444>");
proceedYes = false;
MenuLists screen = new MenuLists(10);
//UiApplication.getUiApplication().pushScreen(homeScreen);
ScreenController screenController = ScreenController.getInstance();
screenController.setCurrentScreen(SignIn.this);
screenController.addNewScreen(screen);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(">>>>Error " + e.getMessage() + " && " + e.toString() );
}
count++;
}
if(proceedYes)
{
System.out.println(">>>>### 3 ");
Hashtable jj = new Hashtable();
boolean proceedNow = false;
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Setting up our account. Please Wait");
}
}
else
{
System.out.println(">>>>### o ");
Hashtable jj = new Hashtable();
boolean proceedNow=false;
System.out.println(">>>>### 4 ");
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
proceedNow = true;
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Please Wait");
}
}
return super.navigationClick(status, time);
}
};
final LabelField registerButton = new LabelField("", Field.FOCUSABLE)
{
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
int hColor;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
XYRect left_edgeH=new XYRect(0, 0, vount, left.getHeight()+2);
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth()) + 2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Create An Account"))/2;
g.drawText("Create An Account", width, height);
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
RegisterScreen registerScreen = new RegisterScreen();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(registerScreen);
return super.navigationClick(status, time);
}
};
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
spaceHolder2.add(loginButton);
spaceHolder2.add(registerButton);
//spaceHolder2.add(registerButton);
spaceHolder1.add(contentHolderPix);
everythingPanel.add(spaceHolder1);
contentHolder1.add(usernameFieldHolder);
contentHolder1.add(passwordFieldHolder);
/*passwordFieldDummyHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_GAINED)
{
contentHolder1.replace(passwordFieldDummyHolder, passwordFieldHolder);
}
}
});
passwordFieldHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_LOST)
{
System.out.println(">>>>>|>>>" + passwordFieldHolder.getIndex());
System.out.println(">>>>>|>>>" + passwordFieldDummyHolder.getIndex());
if(passwordField.getText().length()==0)
{
System.out.println(">>>>>1>>>");
passwordFieldDummyHolder = utilNew.generateEditTextField(passwordFieldDummy, true, holderPad2, edHt, edWt, false);
contentHolder1.replace(passwordFieldHolder, passwordFieldDummyHolder);
//loginButton.setFocus();
}
System.out.println(">>>>>2>>>");
System.out.println(">>>>>2>>>");
}
}
});*/
everythingPanel.add(contentHolder1);
everythingPanel.add(spaceHolder2);
add(everythingPanel);
}
I don't know what your problem actually is, but from what I have seen in your sample code it is clear that you are using the UI framework in a way that is not correct. You need to fix these issues before proceeding further.
Here is an example:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
In this case you ask the parent Manager to lay itself out and give it specific sizes to do so. When doing this, you need to be sure that the sizes you are giving the parent class are not bigger than the size you have been given, So it is more correct to code something like:
super.sublayout(Math.min(Display.getWidth(), width),Math.min(Display.getHeight(), height));
What this will do is attempt to layout the Fields that are contained in the Manager, within the confines of the screen space you have told it to use (in this case the size of the screen). Having done this, it will set the actual size that it needs - in other words, at the end of the layout method, VerticalFieldManager will know how big it needs to be and will set that size. Then it returns. And then you do this:
setExtent(Display.getWidth(), Display.getHeight());
Effectively now you have a VerticalFieldManager that thinks it is working in a certain size, and will optimise its painting around that size, and you have potentially given it a different size. This could confuse!
The same comments apply within a Field's layout() method too.
In other words, if you are going to let the super class layout the Fields, then let the super class set the size, otherwise things can be confused.
Here is another, in fact worse, example:
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
Why is this worse? Because of this line:
setMargin(new XYEdges(20, 0, 0, startX));
Remember the point of sublayout is to position all your Fields on the screen. You have invoked the super.sublayout() processing to do this, and then, once it has done it, you suddenly say actually, I want some margins on the Field. Again you are potentially confusing the processing - in the middle of laying out the Fields you are changing one of the factors that is related to laying the Fields out...
I suggest you review the documentation around creating Managers (and presumably Fields) and look to remove any code that is disrupting this process. To assist you in this investigation, I recommend that you start here:
http://supportforums.blackberry.com/t5/Java-Development/MainScreen-explained/ta-p/606644
and then look at these:
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/Create-a-custom-layout-manager-for-a-screen/ta-p/442990
http://supportforums.blackberry.com/t5/Java-Development/Create-custom-fields/ta-p/444962
You do a similar sort of thing in your paint routine. Here is a snippet:
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
...
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
...
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
paint()'s job is to paint, not to position. Your code is supposed to position Fields in your layout (or sublayout) processing. But in the code above, you potentially move and change the size of a Field while it is trying to paint it!!!! This is bound to cause the system some problems.
The general rule in paint() is you do NOT change the Field, you just paint its current contents.
Two other things I will comment on with respect to the paint() code given above.
1) paint() is called often. You really want to minimise the processing done in paint. So don't create an image (see the left image in the code included above) each time you go through it. Create this once and then use paint to paint() the image. Doing excessive work in paint causes performance problems as well as killing the battery. This is the sort of thing you will not notice on the Simulator because it is so fast compared to the device.
2) And be aware that idea when using invalidate() is to repaint the Field. So there is no point calling invalidate() in the middle of paint(). In fact by doing this, you are causing an infinite loop. Each time you call paint(), your code is then using invalidate() to ask the Field to repaint itself, which causes paint() to be invoked, which asks for a invalidate(), ... You get the picture!.
I have pointed out problems in your layout processing and your paint processing. I'm not saying that these problems are in fact directly giving you the issues you see. It might be something else. You have supplied far too much code for me to review it all looking for that needle. If you want us to review code in detail, then I suggest you recreate the problem with a smaller sample of code. In fact I recommend you try to do this, because by cutting out code until the problem disappears, you will find out what actually is causing the problem.
Finally a couple of other points:
A) There is no real difference between doing background painting in paint() or paintBackground(). And in fact the only background painting you seem to do is this:
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
which is absolutely fine in paint(), and I wouldn't bother changing this to use paintBackground() or a Background class. The one issue I have with this code is that fact that you create a new class instance of UtilNew each time paint is invoked (which is a lot). That won't help performance.
B) I would avoid calling Screen.invalidate() in a scroll change listener until you are sure that there is no other way to get the screen painted correctly. As noted, there is a lot of other suspect code in what you have supplied. Correct that before you try Screen.invalidate().

Resources