If I have an Image file (png, bmp, or jpg), and I need to get the data for the ZPL GFA tag, how do I do that?
I would like some example in vb.net or C#
please add this class to your project:
public class zplImageConverter : Component, IBindableComponent
{
private int blackLimit=125;
private int total;
private int widthBytes;
private bool compressHex= false;
public int BlacknessLimitPercentage
{
get
{
return (blackLimit * 100 / 255);
}
set
{
blackLimit = (value * 255 / 100);
}
}
public bool CompressHex
{
get { return compressHex; }
set { compressHex = value; }
}
private Image _image = null;
public Image Image
{
get { return _image; }
set
{
_image = value;
}
}
public string zplValue
{
get
{
return this._image != null ? FromImage( (Bitmap)this._image ) : "^A0,10,8^FDError!";
}
}
#region IBindableComponent Members
private BindingContext bindingContext;
private ControlBindingsCollection dataBindings;
[Browsable( false )]
public BindingContext BindingContext
{
get
{
if (bindingContext == null)
{
bindingContext = new BindingContext();
}
return bindingContext;
}
set
{
bindingContext = value;
}
}
[DesignerSerializationVisibility( DesignerSerializationVisibility.Content )]
public ControlBindingsCollection DataBindings
{
get
{
if (dataBindings == null)
{
dataBindings = new ControlBindingsCollection( this );
}
return dataBindings;
}
}
#endregion
private static Dictionary<int, string> mapCode= new Dictionary<int, string>() {
{ 1,"G"},
{ 2,"H"},
{ 3,"I"},
{ 4,"J"},
{ 5,"K"},
{ 6,"L"},
{ 7,"M"},
{ 8,"N"},
{ 9,"O"},
{ 10, "P"},
{ 11, "Q"},
{ 12, "R"},
{ 13, "S"},
{ 14, "T"},
{ 15, "U"},
{ 16, "V"},
{ 17, "W"},
{ 18, "X"},
{ 19, "Y"},
{ 20, "g"},
{ 40, "h"},
{ 60, "i"},
{ 80, "j"},
{ 100, "k"},
{ 120, "l"},
{ 140, "m"},
{ 160, "n"},
{ 180, "o"},
{ 200, "p"},
{ 220, "q"},
{ 240, "r"},
{ 260, "s"},
{ 280, "t"},
{ 300, "u"},
{ 320, "v"},
{ 340, "w"},
{ 360, "x"},
{ 380, "y"},
{ 400, "z"},
};
public string FromImage( Bitmap image )
{
string cuerpo= createBody(image);
if (compressHex) cuerpo = HexToAscii( cuerpo );
return headDoc() + cuerpo;
}
private string createBody( Bitmap orginalImage )
{
StringBuilder sb = new StringBuilder();
Graphics graphics = Graphics.FromImage( orginalImage);
graphics.DrawImage( orginalImage, 0, 0 );
int height = orginalImage.Height;
int width = orginalImage.Width;
int index = 0;
// int rgb;
int red;
int green;
int blue;
char[] auxBinaryChar = new char[] { '0', '0', '0', '0', '0', '0', '0', '0' };
widthBytes = (width / 8);
if (((width % 8)
> 0))
{
widthBytes = (((int)((width / 8))) + 1);
}
else
{
widthBytes = (width / 8);
}
this.total = (widthBytes * height);
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width ; w++)
{
var rgb = orginalImage.GetPixel( w, h );
red = rgb.R;
green = rgb.G;
blue = rgb.B;
char auxChar = '1';
int totalColor = (red + green + blue)/3;
if ((totalColor > blackLimit || rgb.A<= blackLimit)) auxChar = '0';
auxBinaryChar[index] = auxChar;
index++;
if (((index == 8) || (w == (width - 1))))
{
sb.Append( ByteBinary( new string( auxBinaryChar ) ) );
auxBinaryChar = new char[] { '0', '0', '0', '0', '0', '0', '0', '0' };
index = 0;
}
}
sb.Append( "\n" );
}
return sb.ToString();
}
private string ByteBinary( string binary )
{
int dec = Convert.ToInt32(binary, 2);//int.Parse(binaryStr);//Integer.parseInt(binaryStr,2);
if (dec > 15)
{
return dec.ToString( "X" ).ToUpper();//int.toString( dec, 16 ).toUpperCase();
}
else
{
return "0" + dec.ToString( "X" ).ToUpper();//Integer.toString( dec, 16 ).toUpperCase();
}
}
private string HexToAscii( string code )
{
int maxlinea = widthBytes * 2;
StringBuilder sbCode = new StringBuilder();
StringBuilder sbLinea = new StringBuilder();
String previousLine = null;
int counter = 1;
char aux = code[0];
bool firstChar = false;
for (int i = 1; i < code.Length; i++)
{
var d=code[i];
if (firstChar)
{
aux = code[i];
firstChar = false;
continue;
}
if (code[i] == '\n')
{
if (counter >= maxlinea && aux == '0')
{
sbLinea.Append( "," );
}
else if (counter >= maxlinea && aux == 'F')
{
sbLinea.Append( "!" );
}
else if (counter > 20)
{
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLinea.Append( mapCode[multi20] );
if (resto20 != 0)
{
sbLinea.Append( mapCode[resto20] + aux );
}
else
{
sbLinea.Append( aux );
}
}
else
{
sbLinea.Append( mapCode[counter] + aux );
if (mapCode[counter] == null) { }
}
counter = 1;
firstChar = true;
if (sbLinea.ToString().Equals( previousLine ))
{
sbCode.Append( ":" );
}
else
{
sbCode.Append( sbLinea.ToString() );
}
previousLine = sbLinea.ToString();
sbLinea.Clear();//.setLength( 0 );
continue;
}
if (aux == code[i])
{
counter++;
}
else
{
if (counter > 20)
{
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLinea.Append( mapCode[multi20] );
if (resto20 != 0)
{
sbLinea.Append( mapCode[resto20] + aux );
}
else
{
sbLinea.Append( aux );
}
}
else
{
sbLinea.Append( mapCode[counter] + aux );
}
counter = 1;
aux = code[i];
}
}
return sbCode.ToString();
}
private String headDoc()
{
String str = "^GFA,"+ total + ","+ total + "," + widthBytes +", \n";
return str;
}
}
then to use:
zplImageConverter cvt= new zplImageConverter();
cvt.Image = Properties.Resources.images;//Set Image to convert
cvt.CompressHex = true;// Enable compresion HexString
cvt.BlacknessLimitPercentage = 50;// Configure the porcentaje for ilumination
Console.WriteLine( cvt.zplValue );// Print on Screen the zplCode (add ^XA before and ^XZ after and try on http://labelary.com/viewer.html)
labelary.com
Related
I have tried first google translation in larvel [
Full Name الاسم الكامل
(Required)
-->
<input type="text" class="form-control" dir="rtl" v-model="text1" #keyup="arabicValue( text1)" id= "text1">
arabicValue: function(txt,text1) {
console.log(txt + "txt");
let char;
// char = txt.value;
char = txt;
console.log(char + "in");
char = char.replace(/`/g, "ذ");
char = char.replace(/0/g, "۰");
char = char.replace(/1/g, "۱");
char = char.replace(/2/g, "۲");
char = char.replace(/3/g, "۳");
char = char.replace(/4/g, "٤");
char = char.replace(/5/g, "۵");
char = char.replace(/6/g, "٦");
char = char.replace(/7/g, "۷");
char = char.replace(/8/g, "۸");
char = char.replace(/9/g, "۹");
char = char.replace(/0/g, "۰");
char = char.replace(/q/g, "ف");
char = char.replace(/w/g, "ث");
char = char.replace(/e/g, "ه");
char = char.replace(/r/g, "ص");
char = char.replace(/t/g, "ط");
char = char.replace(/y/g, "ذ");
char = char.replace(/u/g, "ش");
char = char.replace(/i/g, "أنا");
char = char.replace(/o/g, "ا");
char = char.replace(/p/g, "ص");
char = char.replace(/\[/g, "ج");
char = char.replace(/\]/g, "د");
char = char.replace(/a/g, "أ");
char = char.replace(/s/g, "س");
char = char.replace(/d/g, "د");
char = char.replace(/f/g, "ب");
char = char.replace(/g/g, "ز");
char = char.replace(/h/g, "ح");
char = char.replace(/j/g, "ي");
char = char.replace(/k/g, "ك");
char = char.replace(/l/g, "ل");
char = char.replace(/\;/g, "ك");
char = char.replace(/\'/g, "ط");
char = char.replace(/z/g, "ض");
char = char.replace(/x/g, "ء");
char = char.replace(/c/g, "ج");
char = char.replace(/v/g, "الخامس");
char = char.replace(/b/g, "ب");
char = char.replace(/n/g, "ن");
char = char.replace(/m/g, "م");
char = char.replace(/\,/g, "و");
char = char.replace(/\./g, "ز");
char = char.replace(/\//g, "ظ");
char = char.replace(/~/g, " ّ");
char = char.replace(/Q/g, "َ");
char = char.replace(/W/g, "ً");
char = char.replace(/E/g, "ُ");
char = char.replace(/R/g, "ٌ");
char = char.replace(/T/g, "ط");
char = char.replace(/Y/g, "إ");
char = char.replace(/U/g, "‘");
char = char.replace(/I/g, "÷");
char = char.replace(/O/g, "×");
char = char.replace(/P/g, "؛");
char = char.replace(/A/g, "ِ");
char = char.replace(/S/g, "ٍ");
char = char.replace(/G/g, "لأ");
// char = char.replace(/H/g, "أ");
char = char.replace(/J/g, "ـ");
char = char.replace(/K/g, "،");
char = char.replace(/L/g, "/");
char = char.replace(/Z/g, "~");
char = char.replace(/X/g, "ْ");
char = char.replace(/B/g, "لآ");
char = char.replace(/N/g, "آ");
char = char.replace(/M/g, "’");
char = char.replace(/\?/g, "؟");
text1 = char;
this.text1 = text1;
console.log(text1 + "after");
}`enter code here`
]1and then also tried char replacement in arabic from english on user input and problem is there is no right conversion from english to arabic.is there any way to get exact right arabic characters on user input.
PHP:
For Numbers:
$inputNumbers = $numbers;
$arabic_numbers = ['٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١','٠'];
$num = range(0, 9);
$arabic_numbers_output = str_replace($arabic_numbers , $num, $inputNumbers);
For Letters:
$inputText = $text;
$arabic_letters = ['آ', 'ب', 'ج']; // and so on ...
$letters = ['A', 'B', 'J']; // and so on ...
$arabic_letters_output = str_replace($arabic_letters , $letters , $inputText);
JS:
For Numbers:
String.prototype.toArabicDigit= function()
{
var id= ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
return this.replace(/[0-9]/g, function(w){ return id[+w] });
}
var en_number = "0123456789";
alert(en_number.toArabicDigit());
For Letters:
(This is for Farsi but you can modify it to match with Arabic)
if (typeof HTMLElement!="undefined" && ! HTMLElement.prototype.insertAdjacentElement) {
HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
switch (where) {
case 'beforeBegin':
this.parentNode.insertBefore(parsedNode,this)
break;
case 'afterBegin':
this.insertBefore(parsedNode,this.firstChild);
break;
case 'beforeEnd':
this.appendChild(parsedNode);
break;
case 'afterEnd':
if (this.nextSibling)
this.parentNode.insertBefore(parsedNode,this.nextSibling);
else
this.parentNode.appendChild(parsedNode);
break;
}
}
HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var parsedHTML = r.createContextualFragment(htmlStr);
this.insertAdjacentElement(where,parsedHTML)
}
HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
var parsedText = document.createTextNode(txtStr)
this.insertAdjacentElement(where,parsedText)
}
}
var FarsiType = {
// Farsi keyboard map based on Iran Popular Keyboard Layout
farsiKey: [
32, 33, 34, 35, 36, 37, 1548, 1711,
41, 40, 215, 43, 1608, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 1705, 44, 61, 46, 1567,
64, 1616, 1584, 125, 1609, 1615, 1609, 1604,
1570, 247, 1600, 1548, 47, 8217, 1583, 215,
1563, 1614, 1569, 1613, 1601, 8216, 123, 1611,
1618, 1573, 126, 1580, 1688, 1670, 94, 95,
1662, 1588, 1584, 1586, 1740, 1579, 1576, 1604,
1575, 1607, 1578, 1606, 1605, 1574, 1583, 1582,
1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589,
1591, 1594, 1592, 60, 124, 62, 1617
],
Type: true,
counter: 0,
ShowChangeLangButton: 1, // 0: Hidden / 1: Visible
KeyBoardError: 0, // 0: Disable FarsiType / 1: Show Error
ChangeDir: 2, // 0: No Action / 1: Do Rtl-Ltr / 2: Rtl-Ltr button
UnSupportedAction: 0 //0: Disable FarsiType / 1: Low Support
}
FarsiType.enable_disable = function(Dis) {
var invis, obj;
if (!Dis.checked) {
FarsiType.Type = true;
disable = false;
color = 'darkblue';
} else {
FarsiType.Type = false;
disable = true;
color = '#ECE9D8';
}
if (FarsiType.ShowChangeLangButton == 1) {
for (var i=1; i<= FarsiType.counter; i++) {
obj = document.getElementById('FarsiType_button_' + i);
obj.disabled = disable;
obj.style.backgroundColor = color;
}
}
}
FarsiType.Disable = function() {
FarsiType.Type = false;
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
Dis.checked = true;
}
if (FarsiType.ShowChangeLangButton == 1) {
for (var i=1; i<= FarsiType.counter; i++) {
obj = document.getElementById('FarsiType_button_' + i);
obj.disabled = true;
obj.style.backgroundColor = '#ECE9D8';
}
}
}
FarsiType.init = function() {
var Inputs = document.getElementsByTagName('INPUT');
for (var i=0; i<Inputs.length; i++) {
if (Inputs[i].type.toLowerCase() == 'text' && (Inputs[i].lang.toLowerCase() == 'fa' || Inputs[i].lang.toLowerCase() == 'fa-ir')) {
FarsiType.counter++;
new FarsiType.KeyObject(Inputs[i], FarsiType.counter);
}
}
var Areas = document.getElementsByTagName('TEXTAREA');
for (var i=0; i<Areas.length; i++) {
if (Areas[i].lang.toLowerCase() == 'fa' || Areas[i].lang.toLowerCase() == 'fa-ir') {
FarsiType.counter++;
new FarsiType.KeyObject(Areas[i], FarsiType.counter);
}
}
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
FarsiType.enable_disable (Dis);
Dis.onclick = new Function( "FarsiType.enable_disable (this);" )
}
}
FarsiType.KeyObject = function(z,x) {
GenerateStr = "";
if (FarsiType.ShowChangeLangButton == 1) {
GenerateStr = GenerateStr + "<input type='button' id=FarsiType_button_"+x+" style='border: none; background-color:darkblue; font-size:11; color:white; font-family:tahoma; padding: 1px; margin: 1px; width: auto; height: auto;' value='FA' /> ";
}
if (FarsiType.ChangeDir == 2) {
GenerateStr = GenerateStr + "<input type='button' id=FarsiType_ChangeDir_"+x+" style='border: none; background-color:darkblue; font-size:11; color:white; font-family:tahoma; padding: 1px; margin: 1px; width: auto; height: auto;' value='RTL' />"
}
z.insertAdjacentHTML("afterEnd", GenerateStr);
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm = document.getElementById ('FarsiType_button_' + x);
z.bottelm.title = 'Change lang to english';
}
if (FarsiType.ChangeDir == 2) {
z.Direlm = document.getElementById ('FarsiType_ChangeDir_' + x);
}
z.farsi = true;
z.dir = "rtl";
z.align = "right";
z.style.textAlign = z.align;
z.style.direction = z.dir;
setSelectionRange = function(input, selectionStart, selectionEnd) {
input.focus()
input.setSelectionRange(selectionStart, selectionEnd)
}
ChangeDirection = function() {
if (z.dir == "rtl") {
z.dir = "ltr";
z.align = "left";
z.Direlm.value = "LTR";
z.Direlm.title = "Change direction: Right to Left"
} else {
z.dir = "rtl";
z.align = "right";
z.Direlm.value = "RTL";
z.Direlm.title = "Change direction: Left to Right"
}
z.style.textAlign = z.align;
z.style.direction = z.dir;
z.focus();
}
ChangeLang = function(e, ze) {
if(ze)
z = ze;
if (FarsiType.Type) {
if (z.farsi) {
z.farsi = false;
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm.value = "EN";
z.bottelm.title = 'Change lang to persian';
}
if (FarsiType.ChangeDir == 1) {
z.style.textAlign = "left";
z.style.direction = "ltr";
}
} else {
z.farsi = true;
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm.value = "FA";
z.bottelm.title = 'Change lang to english';
}
if (FarsiType.ChangeDir == 1) {
z.style.textAlign = "right";
z.style.direction = "rtl";
}
}
z.focus();
}
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
return false;
}
Convert = function(e) {
if (e == null)
e = window.event;
var key = e.which || e.charCode || e.keyCode;
var eElement = e.target || e.originalTarget || e.srcElement;
if (e.ctrlKey && key == 32) {
ChangeLang(e, z);
}
if (FarsiType.Type) {
if (
(e.charCode != null && e.charCode != key) ||
(e.which != null && e.which != key) ||
(e.ctrlKey || e.altKey || e.metaKey) ||
(key == 13 || key == 27 || key == 8)
) return true;
//check windows lang
if (key > 128) {
if (FarsiType.KeyBoardError == 0) {
FarsiType.Disable();
} else {
alert("Please change your windows language to English");
return false;
}
}
// If Farsi
if (FarsiType.Type && z.farsi) {
//check CpasLock
if ((key >= 65 && key <= 90&& !e.shiftKey) || (key >= 97 && key <= 122 ) && e.shiftKey) {
alert("Caps Lock is On. To prevent entering farsi incorrectly, you should press Caps Lock to turn it off.");
return false;
}
// Shift-space -> ZWNJ
if (key == 32 && e.shiftKey)
key = 8204;
else
key = FarsiType.farsiKey[key-32];
key = typeof key == 'string' ? key : String.fromCharCode(key);
// to farsi
try {
var docSelection = document.selection;
var selectionStart = eElement.selectionStart;
var selectionEnd = eElement.selectionEnd;
if (typeof selectionStart == 'number') {
//FOR W3C STANDARD BROWSERS
var nScrollTop = eElement.scrollTop;
var nScrollLeft = eElement.scrollLeft;
var nScrollWidth = eElement.scrollWidth;
eElement.value = eElement.value.substring(0, selectionStart) + key + eElement.value.substring(selectionEnd);
setSelectionRange(eElement, selectionStart + key.length, selectionStart + key.length);
var nW = eElement.scrollWidth - nScrollWidth;
if (eElement.scrollTop == 0) { eElement.scrollTop = nScrollTop }
} else if (docSelection) {
var nRange = docSelection.createRange();
nRange.text = key;
nRange.setEndPoint('StartToEnd', nRange);
nRange.select();
}
} catch(error) {
try {
// IE
e.keyCode = key
} catch(error) {
try {
// OLD GECKO
e.initKeyEvent("keypress", true, true, document.defaultView, false, false, true, false, 0, key, eElement);
} catch(error) {
//OTHERWISE
if (FarsiType.UnSupportedAction == 0) {
alert('Sorry! no FarsiType support')
FarsiType.Disable();
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
Dis.disabled = true;
}
return false;
} else {
eElement.value += key;
}
}
}
}
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
}
return true;
}
if (FarsiType.ShowChangeLangButton == 1) { z.bottelm.onmouseup = ChangeLang; }
if (FarsiType.ChangeDir == 2) { z.Direlm.onmouseup = ChangeDirection; }
z.onkeypress = Convert;
}
if (window.attachEvent) {
window.attachEvent('onload', FarsiType.init)
} else if (window.addEventListener) {
window.addEventListener('load', FarsiType.init, false)
}
I have a SWT Treeviewer with custom labelprovider. But it flickers while scrolling even if it is not very large. I think it is because of the paint method. How can I improve performance of the it.
Thank you in advance.
Here is my paint method :
public class TreeLabelProvider extends OwnerDrawLabelProvider {
public ImageData[] getImage(Object element) {
//This function just have if else to return corrent imageData
}
public String getText(Object element) {
//This function also just have if else to return matching text to display
}
#Override
protected void measure(Event event, Object element) {
TreeItem item = (TreeItem) event.item;
Tree tree = item.getParent();
ImageData[] images = getImage(element);
int imgWidht = 0;
int imgHeight = 0;
if (images != null) {
for (int i = 0; i < images.length; i++) {
imgWidht += images[i].width;
int imgHeightTemp = images[i].height;
if (imgHeightTemp > imgHeight) {
imgHeight = imgHeightTemp;
}
}
}
if (!event.gc.isDisposed()) {
Point point = event.gc.textExtent(getText(element));
int rectangleWidth = 0;
rectangleWidth = imgWidht + point.x + 10;
event.setBounds(new Rectangle(event.x, event.y, rectangleWidth, imgHeight));
event.height = imgHeight + 3;
}
}
#Override
protected void paint(Event event, Object element) {
Rectangle bounds = event.getBounds();
int imgWidth = 0;
int x = bounds.width > 0 ? bounds.x + bounds.width : bounds.x;
ImageData[] img = getImage(element);
if (img != null) {
for (int imgIndex = 0; imgIndex < img.length; imgIndex++) {
event.gc.setAntialias(SWT.ON);
// make the image transparent
ImageData ideaData = img[imgIndex];
int whitePixel = ideaData.palette.getPixel(new RGB(255, 255, 255));
ideaData.transparentPixel = whitePixel;
Image transparentIdeaImage = new Image(Display.getDefault(), ideaData);
if (imgIndex > 0) {
event.gc.drawImage(transparentIdeaImage,
x + transparentIdeaImage.getBounds().width - 4, bounds.y + 2);
} else {
event.gc.drawImage(transparentIdeaImage, x - 5, bounds.y + 2);
}
imgWidth += transparentIdeaImage.getBounds().width;
// dispose Image
transparentIdeaImage.dispose();
}
}
event.gc.drawText(getText(element), x + imgWidth + 1, bounds.y + 3, true);
}
#Override
protected void erase(Event event, Object element) {}
}
I am making a game in Eclipse Mars using the Processing library. I had made the game elsewhere and it ran fine. There were no errors after I copied and pasted the files from my flash drive to the folder in Eclipse. When I tried to run it, it said "The selection cannot be launched, and there are no recent launches." There were no recent launches because I had just gotten Eclipse. My code is as follows:
Main Class:
//package dogeball;
import processing.core.PApplet;
import processing.core.PImage;
import java.awt.Color;
import processing.core.PFont;
public class Dogeball extends PApplet {
Ball ball;
Furniture butterChair;
Furniture[] bricks;
PFont dogefont;
float py;
float score;
boolean game;
int checker;
boolean mode;
PImage img = loadImage("doge.jpg");
PImage img2 = loadImage("doge2.png");
public void setup() {
checker = 0;
size(300,250);
game = false;
mode = true;
ball = new Ball(this, 100, 225, 0, 0, 10, Color.DARK_GRAY );
butterChair = new Furniture(this, 130, 238, 40, 10, Color.YELLOW);
py = butterChair.w /2;
bricks = new Furniture[56];
dogefont = loadFont("ComicSansMS-48.vlw");
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
public void draw() {
if(game == false) {
background(img);
fill(0,255,255);
textSize(30);
textFont(dogefont);
text("DogeBall",33, 170);
fill(255,255,0);
textSize(20);
text("Press Space", 120,190);
fill(255,0,0);
text("Such BrickBreaker", 20, 20);
fill(0,0,255);
text("Much Atari", 190, 80);
fill(0,255,0);
text("How Breakout", 150, 230);
}
if(keyPressed == true) {
if (key == ' ') {
game = true;
}
}
if(game == true) {
if(keyPressed == true) {
if (key == 'm') {
mode = !mode;
}
}
//checker = 0;
background(img);
ball.appear();
ball.hover();
butterChair.appear();
if(mode == true) {
butterChair.x = mouseX-butterChair.w/2;
}
if(mode == false) {
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == LEFT){
butterChair.x -= 3;
}
}
}
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == RIGHT){
butterChair.x += 3;
}
}
}
}
if(butterChair.x <= 0) {
butterChair.x = 0;
}
if(butterChair.x >= width - butterChair.w) {
butterChair.x = width - butterChair.w;
}
textFont(dogefont);
fill(255,0,255);
text("Much Doge", 12, 160);
fill(255,0,0);
textSize(20);
text("M to toggle mouse mode.", 20,200);
fill(0);
textSize(10);
text("You might have to press twice", 10,220);
fill(0,0,255);
textSize(20);
text("Press S to Start", 150, 230);
if (keyPressed == true) {
if (key == 's' || key == 'S'){
ball.vy = 2;
ball.vx = 1;
}
}
/*if(mousePressed == true) {
ball.vx = 0;
ball.vy = 0;
}*/
for(int i = 0; i<56; i+= 1) {
bricks[i].appear();
}
}
detectCollision();
if(ball.y >= height) {
checker = 0;
if(checker ==0){
background(img);
ball.vx = 0;
ball.vy = 0;
textSize(30);
fill(255,0,0);
game = false;
text("Such Sorry", 130, 160);
fill(0,255,255);
text("Much Game Over", 20, 215);
fill(255,255,0);
text("So Losing", 10, 30);
textSize(20);
text("Press P to Play Again", 20, 245);
}
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
void detectCollision() {
if(keyPressed == true) {
if(key == '-')
{
for(int cCode = 0; cCode < 56; cCode += 1) {
Furniture b = bricks[cCode];
b.x = width * 2;
b.y = height * 2;
score = 56;
}
}}
if(ball.x >= butterChair.x &&
ball.x <= butterChair.x + butterChair.w &&
ball.y + ball.s /2 > butterChair.y) {
ball.vy *= -1;
}
for(int i = 0; i<bricks.length; i+= 1) {
Furniture b = bricks[i];
if(ball.x >= b.x && ball.x <= b.x+b.w && ball.y-ball.s/2 <= b.y) {
b.y = height * 2;
b.x = width * 2;
ball.vy *= -1;
score += 1;
}
if(score == 56){
background(img);
ball.vx = 0;
ball.vy = 0;
fill(255,0,0);
textSize(20);
text("Such Winning!", 20, 20);
textSize(40);
fill(0,255,0);
text("Much Congrats!",12 ,160);
textSize(20);
fill(255,0,255);
text("Press P to Play Again", 20, 245);
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
}
static public void main(String args[]) {
PApplet.main("Dogeball");
}
}
Ball Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Ball extends PApplet {
float x;
float y;
float vx;
float vy;
float s;
Color c;
PApplet p;
Ball(PApplet pApp, float xLocation, float yLocation, float xSpeed, float ySpeed, float size, Color shade){
x = xLocation;
y = yLocation;
vx = xSpeed;
vy = ySpeed;
s = size;
c = shade;
p = pApp;
}
void hover() {
x += vx;
y += vy;
if(x< 0 || x> p.width) {
vx *= -1;
}
if(y< 0) {
vy *= -1;
}
}
void appear() {
p.fill(c.getRGB() );
p.ellipse(x,y,s,s);
}
}
Paddle Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Furniture extends PApplet {
float x;
float y;
float w;
float h;
Color c;
PApplet p;
Furniture(PApplet PApp, float locationX, float locationY, float fWidth, float fHeight, Color shade) {
x = locationX;
y = locationY;
w = fWidth;
h = fHeight;
c = shade;
p = PApp;
}
void appear() {
p.fill(c.getRGB());
p.rect(x,y,w,h);
}
}
You have probably the wrong project selected on the projects tree or the run configurations are set to another project, since you haven't run it yet.
Either way, you have to right click your projects folder on the projects tree, then find Run As > Java Applet.
Another way to do it would be adding a main function, as you already did, and run is as a Java Application. Instead of using the current main function, you can try to use the code below to see it in present mode and see if it works:
public static void main(String args[]) {
PApplet.main(new String[] { "--present", "Dogeball" });
}
I am trying to generate some random text using processing, what I want is that everytime I press the mouse new text is generated and is displayed on the screen. As of now the text is simply generated than it gets removed due to the looping of draw() any way to fix this?
int click = 0;
void setup() {
String alfabet = "abcdefghijklmnopqrstuvw";
size(1000,1000);
textSize(64);
textAlign(CENTER);
}
void draw() {
background(0);
if(click==1) {
click = 0;
genereren();
}
}
void genereren() {
String alfabet = "abcdefghijklmnopqrstuvw";
int x = 10;
for(int i = 0; i < 15; i = i+1) {
float r = random(24);
if(r < 1) {
r = r+1;
}
int d = int(r);
String EersteLetter = alfabet.substring(d-1,d);
if ( i <= 4) {
text(EersteLetter, 60+(x*3*i), 80);
}
if ( i <= 8) {
text(EersteLetter, 60+(x*3*i), 120);
}
if ( i <= 12) {
text(EersteLetter, 60+(x*3*i), 160);
}
if ( i <= 16) {
text(EersteLetter, 60+(x*3*i), 200);
}
}
}
void mouseClicked() {
click = 1;
}
try this example, if you click the mouse it will display or not, if you hold the mouse button you will freeze the current text.
boolean click = false;
void setup() {
String alfabet = "abcdefghijklmnopqrstuvw";
size(1000, 1000);
textSize(64);
textAlign(CENTER);
background(0);
}
void draw() {
if (click) {
genereren();
}
}
void mousePressed() {
if (mouseButton == LEFT) {
genereren();
}
}
void genereren() {
background(0);
String alfabet = "abcdefghijklmnopqrstuvw";
int x = 10;
for (int i = 0; i < 15; i = i+1) {
float r = random(24);
if (r < 1) {
r = r+1;
}
int d = int(r);
String EersteLetter = alfabet.substring(d-1, d);
if ( i <= 4) {
text(EersteLetter, 60+(x*3*i), 80);
}
if ( i <= 8) {
text(EersteLetter, 60+(x*3*i), 120);
}
if ( i <= 12) {
text(EersteLetter, 60+(x*3*i), 160);
}
if ( i <= 16) {
text(EersteLetter, 60+(x*3*i), 200);
}
}
}
void mouseReleased() {
clear();
}
void mouseClicked() {
click=!click;
}
The easiest way to do this would be just by not using the "background(0);", this way the text would stay for ever. Then you could add a button that runs a method whit the "background(0);" to erase all text.
I'm having an interesting anomaly when displaying a listfield on the blackberry simulator:
The top item is the height of a single line of text (about 12 pixels) while the rest are fine.
Does anyone know why only the top item is being drawn this way? Also, when I add an empty venue in position 0, it still displays the first actual venue this way (item in position 1).
Not sure what to do.
Thanks for any help.
The layout looks like this:
-----------------------------------
| *part of image* | title |
-----------------------------------
| | title |
| * full image * | address |
| | city, zip |
-----------------------------------
The object is called like so:
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Here is the drawListRow code:
public void drawListRow( ListField listField, Graphics graphics,
int index, int y, int width )
{
listField.setRowHeight(90);
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String image_url = (String) item.get("image_url");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = null;
try
{
String filename = image_url.substring(image_url.indexOf("crop/")
+ 5, image_url.length() );
FileConnection fconn = (FileConnection)Connector.open(
"file:///SDCard/Blackberry/project1/" + filename,
Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(
data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
}
else
{
}
}
}
catch(IOException ef)
{
}
graphics.drawText( venue_name, 140, y, 0, width );
graphics.drawText( address, 140, y + 15, 0, width );
graphics.drawText( city + ", " + zip, 140, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y, img.getWidth(), img.getHeight(),
img, 0, 0, 0);
}
}
setRowHeight should be called once after construction of ListField, not inside of drawListRow on each time row is repainted:
listField = new ListField( venueList.size() );
listField.setRowHeight(90);
listField.setCallback( this );
listField.setSelectedIndex(-1);
_middle.add( listField );
Aman,
Hopefully you can use this for something. You should be able to extract the list field data from this wildly out of control class. Remember, this is a work in progress, so you will have to strip out the things that are quite clearly custom to my app. Like the image handling that relies on a substring for a file name.
It works fine for me, but it will totally not work for anyone htat just copies and pastes, so good luck...
package venue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
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.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
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.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class categoryView extends MainScreen implements FieldChangeListener, ListFieldCallback, FocusChangeListener {
private HorizontalFieldManager _top;
private HorizontalFieldManager _nav;
private VerticalFieldManager _middle;
private int horizontalOffset;
private final static long animationTime = 300;
private long animationStart = 0;
private int venue_id;
private int category_id;
private CustomButtonField rectangle;
private Vector venueList = new Vector();
private Hashtable venue_index = new Hashtable();
private Vector image_index = new Vector();
private ListField listField;
private int last_menu_item = 2;
private int last_nav = 2;
private int before_last = 1;
private int location_count = 0;
private int img_width = 120;
private int img_height = 80;
private Field f;
public categoryView(int id) {
super();
category_id = id;
horizontalOffset = Display.getWidth();
_top = new HorizontalFieldManager(Manager.USE_ALL_WIDTH | Field.FIELD_HCENTER)
{
public void paint(Graphics gr)
{
Bitmap bg = Bitmap.getBitmapResource("bg.png");
gr.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), bg, 0, 0);
subpaint(gr);
}
};
_nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
_middle = new VerticalFieldManager();
add(_top);
add(_nav);
add(_middle);
Bitmap lol = Bitmap.getBitmapResource("logo.png");
BitmapField lolfield = new BitmapField(lol);
_top.add(lolfield);
HorizontalFieldManager nav = new HorizontalFieldManager(Field.USE_ALL_WIDTH | Manager.HORIZONTAL_SCROLL);
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration ne = locations.keys();
Enumeration nv = locations.elements();
int counter = 1;
if(locations.size() > 1)
{
counter = locations.size() - 1;
}
int count = 1;
while(ne.hasMoreElements())
{
final String location_id = ne.nextElement().toString();
String location = nv.nextElement().toString();
last_nav = Integer.parseInt(location_id);
rectangle = new CustomButtonField(location_id, location, 25, Field.FOCUSABLE);
rectangle.setFocusListener(this);
nav.add(rectangle);
if(count == counter)
{
before_last = Integer.parseInt(location_id);
}
count ++;
}
_nav.add(nav);
}
public void setDefaultLocation()
{
Vector locs = getLocations();
Hashtable loc1 = (Hashtable) locs.elementAt(0);
Enumeration er = loc1.keys();
Enumeration vr = loc1.elements();
int i = 0;
while(er.hasMoreElements())
{
final String location_id = er.nextElement().toString();
if(i == 0)
{
last_menu_item = Integer.parseInt(location_id);
}
i ++;
}
}
public void drawMiddle()
{
Vector venues = getVenues(category_id);
Hashtable venue_list = (Hashtable) venues.elementAt(0);
Enumeration e = venue_list.keys();
Enumeration v = venue_list.elements();
int count = 0;
while(e.hasMoreElements())
{
String vid = e.nextElement().toString();
Hashtable elm = (Hashtable)v.nextElement();
venueList.addElement(elm);
venue_index.put(Integer.toString(count), (String) elm.get("venue_id"));
EncodedImage img = null;
String image_url = (String) elm.get("image_url");
try
{
String filename;
if(image_url.length() > 5)
{
filename = image_url.substring( image_url.indexOf("crop/") + 5, image_url.length() );
}
else
{
filename = "1.png";
}
FileConnection fconn = (FileConnection) Connector.open( "file:///SDCard/Blackberry/venue/" + filename, Connector.READ);
if ( !fconn.exists() )
{
}
else
{
InputStream input = fconn.openInputStream();
byte[] data = new byte[(int)fconn.fileSize()];
input.read(data);
input.close();
if(data.length > 0)
{
EncodedImage rawimg = EncodedImage.createEncodedImage(data, 0, data.length);
int dw = Fixed32.toFP(Display.getWidth());
int iw = Fixed32.toFP(rawimg.getWidth());
int sf = Fixed32.div(iw, dw);
img = rawimg.scaleImage32(sf * 4, sf * 4);
img_width = (int) Math.ceil(Display.getWidth() / 4);
img_height = (int) Math.ceil(Display.getWidth() / 6);
}
else
{
}
}
}
catch(IOException ef)
{
}
image_index.addElement(img);
count ++;
}
final int count_results = count;
_middle = new VerticalFieldManager( Manager.VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(0xFFFFFF);
graphics.setColor(Color.BLACK);
graphics.clear();
super.paint(graphics);
}
protected void sublayout(int maxWidth, int maxHeight)
{
int displayWidth = Display.getWidth();
//int displayHeight = Display.getHeight();
int displayHeight = count_results * img_height;
super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};
add(_middle);
listField = new ListField( venueList.size() );
listField.setCallback( this );
listField.setSelectedIndex(-1);
listField.setRowHeight(img_height);
_middle.add( listField );
_middle.add(new RichTextField(Field.NON_FOCUSABLE));
}
public boolean navigationClick(int status, int time) {
Field focus = UiApplication.getUiApplication().getActiveScreen() .getLeafFieldWithFocus();
if (focus instanceof ListField) {
int selected = listField.getSelectedIndex();
String venue_id = (String) venue_index.get(Integer.toString(selected));
moveScreens(venue_id);
}
return true;
}
void setListSize()
{
listField.setSize( venueList.size() );
}
public void drawListRow( ListField listField, Graphics graphics, int index, int y, int width )
{
Hashtable item = (Hashtable) venueList.elementAt( index );
String venue_name = (String) item.get("name");
String address = (String) item.get("address");
String city = (String) item.get("city");
String zip = (String) item.get("zip");
EncodedImage img = (EncodedImage) image_index.elementAt(index);
graphics.drawText( venue_name, img_width + 10, y, 0, width );
graphics.drawText( address, img_width + 10, y + 15, 0, width );
graphics.drawText( city + ", " + zip, img_width + 10, y + 30, 0, width );
if(img != null)
{
graphics.drawImage(0, y + 3, img.getWidth(), img.getHeight(), img, 0, 0, 0);
}
}
public Object get( ListField listField, int index )
{
return venueList.elementAt( index );
}
public Vector getCategories()
{
Vector results = new Vector();
database db = new database();
Vector categories = db.getCategories();
if(categories.size() > 0)
results = categories;
return results;
}
public Vector getLocations()
{
Vector results = new Vector();
database db = new database();
Vector subcats = db.getCategoryLocations(category_id);
Hashtable subs = (Hashtable) subcats.elementAt(0);
if(subs.size() > 0)
{
location_count = subs.size();
results = subcats;
}
return results;
}
public Vector getVenues(int category_id)
{
Vector results = new Vector();
database db = new database();
Vector venues = db.getLocationVenues(category_id, last_menu_item);
if(venues.size() > 0)
results = venues;
return results;
}
protected void makeMenu(Menu menu, int instance)
{
super.makeMenu(menu, instance);
menu.add(new MenuItem("Home", 10, 20){
public void run()
{
moveScreens("main");
}
});
menu.add(new MenuItem("Search", 10, 20){
public void run()
{
Dialog.inform("Search was clicked.");
}
});
Vector locs = getLocations();
Hashtable locations = (Hashtable) locs.elementAt(0);
Enumeration e = locations.keys();
Enumeration v = locations.elements();
while(e.hasMoreElements())
{
final String location_id = e.nextElement().toString();
String location = v.nextElement().toString();
menu.add(new MenuItem(location, 10, 20){
public void run()
{
Dialog.inform("Location " + location_id + " was clicked");
}
});
}
}
public void moveScreens(String type)
{
if(type == "main")
{
UiApplication.getUiApplication().popScreen(this);
}
else
{
int venue_id = Integer.parseInt(type);
Screen newScreen = new ViewVenue(venue_id);
UiApplication.getUiApplication().pushScreen(newScreen);
}
}
protected void sublayout(int width, int height)
{
super.sublayout(width, height);
if(horizontalOffset > 0)
{
if(animationStart == 0)
{
animationStart = System.currentTimeMillis();
}
else
{
long timeElapsed = System.currentTimeMillis() - animationStart;
if(timeElapsed >= animationTime)
{
horizontalOffset = 0;
}
else
{
float percentDone = (float)timeElapsed / (float)animationTime;
horizontalOffset = Display.getWidth() - (int)(percentDone * Display.getWidth());
}
}
}
setPosition(horizontalOffset, 0);
if(horizontalOffset > 0)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
updateLayout();
}
});
}
}
public void fieldChanged(Field field, int context)
{
int id = 0;
if (field instanceof CustomButtonField) {
id = ((CustomButtonField)field).getId();
}
venue_id = id;
Dialog.inform(Integer.toString(venue_id));
//moveScreens("venue");
}
public void focusChanged(Field field, int eventType) {
if((eventType == FocusChangeListener.FOCUS_GAINED)) {
if (field instanceof CustomButtonField) {
final int id = ((CustomButtonField)field).getId();
if(id == last_nav && before_last != last_menu_item && last_nav != before_last)
{
//updateContent(id);
f.setFocus();
}
else
{
updateContent(id);
f = field;
}
}
}
}
public void updateContent(final int id)
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
delete(_middle);
venueList.removeAllElements();
image_index.removeAllElements();
last_menu_item = id;
drawMiddle();
}
});
}
public boolean onSavePrompt()
{
// do nothing
return true;
}
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;
}
}