Swing JPanel with background image

This code add an image to Jpanel.

JPanel panel1 = new JPanel();
JFrame recursion_frame = new JFrame();

BackgroundPanel stack_image1 = new BackgroundPanel("Recursion.jpg");

panel1.setLayout(null);
panel1.setLayout(new BorderLayout());
panel1.setBackground(Color.lightGray);
panel1.setVisible(true);
recursion_frame.setContentPane(panel1);  ///adding to panel...
recursion_frame.getContentPane().add(stack_image1);  //adding image to panel...

Position swing window in center of the screen

In some case we need to position the window in the center of the screen . The same effect can be achieved by hard coding the center points .But in that case the window position change when the screen resolution changes

This code will position the window in center irrespective of different screen resolutions

public JFrame stack_frame = new JFrame();
stack_frame.setLocationRelativeTo(null);

What is Objective C Keyword id ?

Hi,

Objective C uses a special keyword ‘id’.
Let’s see what it is.
Objective C -id- is actually a ‘pointer to an object’. That is ‘id’ can hold a pointer to any objective c object. It doesn’t matter the object’s class.
eg:

NSString *myString = @"Coderz Heaven!";
id newString;
NSString *tempString;
newString=myString;
tempString=newString;

That’s it! It will work out with using ‘id’ keyword. Compiler simply thinks ‘you know what you are doing!’

A word of caution : Remember not to use * while creating id objects! Because that type already know it’s a pointer!

Read a plist from your resources folder in Iphone Objective C

Plist or property list are usually used for storing data in iPhone.
They are normal XML files, you can open it in a texteditor to view it’s data.
This sample code shows how to read data from the plist.
Reading a plist will return an array.You can print out the array to view the results.


     NSString *path= [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"];
     BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
     if(fileExists){
         NSMutableArray *arr = [[NSArray alloc]  initWithContentsOfFile: path];
         NSLog(@"Data from plist %@",arr);
     }else {
        NSLog(@"File Not Found");
        exit(1);  // if file not found exit the application.
    }

Please leave your valuable comments………

Remove unwanted memory from iPhone….

Hi all ……
You know iPhone doesnot have garbage collection like ANDROID. So it becomes the responsibility of the developer or programmer to release the resources and remove the unwanted textures from your memory.
If you don’t remove the unused textures and other variables from your memory your application will exit after a while.

You often have the problem that your iPhone application exits unexpectedly, Most probably this may be the reason.

One method to check is…….
1. Release variables declared inside a function from there itself.
2. Release other variables inside the dealloc() function.
3. Remove the textures that remain in memory when you use images.
4. If you are using particle effects then don’t use the particle release function.
5. Unload the sounds on dealloc.

For removing the variables you can use..

[my_var release];

For removing the textures from the memory use this code inside the dellaoc function.
Check out the console if it is working. It will show console outputs such as “removing unused texture bla bla bla..”

/** this will remove all the unused frames if you are using sprite sheets **/
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
/** this will remove unused textures of images if you are using only images **/
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
/** this will remove all textures from memory **/
[[CCTextureCache sharedTextureCache] removeAllTextures];

But still your program may exit. This is due to the second line and put only the this line..

[[CCTextureCache sharedTextureCache] removeUnusedTextures];

This may solve your problem…….
This above code will release most of your unused memory.

Please leave your valuable comments if this post was useful…..

Collision Detection In Box2D – Using With Cocos2D

For an interactive game building using Box2D, collision detection of Box2D bodies is necessary. There is an easy way to implement collision detection in Box2D.

For checking whether two bodies have collided with each other in Box2D while using it with cocos2D, then use the following lines of code where ever you want to check collision.

if((contact.fixtureA == sourceFixture && contact.fixtureB == destinationFixture) ||
(contact.fixtureA == destinationFixture && contact.fixtureB == sourceFixture ))
{
//What you want to do after checking the collision?!!!
//That lines of code goes here!
//Simple and Pretty , isn't it?
}

Here you are cheking whether two box2D fixtures are in contact or not! And you can decide which fixtures you need to check for collision.

:)

Removing Forces From Your World in Box2D Cocos2D

Hi,

In certain situations you may need to remove all the forces you have applied on different bodies in your box2D world.
Then what to do?
Removing all the forces from the bodies in the box2D world is simple. Just use the single line of code.

yourWorld->ClearForces();

Here yourWorld is your Box2D world. Simple, isn’t it?

:)

File Operations in Adobe AIR/FLEX

The following example shows how to deal with a simple text file in Adobe AIR/FLEX.
This example illustratesd how to write a string to a text file and save it in the desktop.
However you can use the “application directory” but make sure that you have necessary write permission to access the directory.




	

Please leave your valuable comments…..

How to turnOff suggestions in editText in ANDROID?

Sometimes we may not need suggestions to appear in the textbox in our application in ANDROID.
This simple codes turns off this suggestion ….
Put this code inside your editText tag in the layout xml file.

android:inputType="textNoSuggestions"

if the above code is not working try this…

android:inputType="textNoSuggestions|textVisiblePassword"

Please leave your valuable comments………..

Creating a JMenubar in java swing

Creating a JMenubar is simple.

        JMenuBar  menubar = new JMenuBar();
	JMenu menu1 = new JMenu("File");
	JMenu menu2= new JMenu("Help");
	file = new JMenuItem("Exit to menu");
	edit = new JMenuItem("Exit");

	JMenuItem about = new JMenuItem("About us");
	f.setJMenuBar(menubar);
	menu1.add(file);
	menu1.add(edit);
	menu2.add(about);
	menubar.add(menu1);
	menubar.add(menu2);

	file.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action......
		}
	});
	edit.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action.....
		}
	});
	about.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action....
		}
	});

Unscheduling All Selector Functions in Cocos2D iPhone

There may arise certain situations there you are using a number of @selector functions and want to stop all those selectors. In cocos2D there is an easy way to stop/unschedule all the selectors with a single line of code!

Use this line of code where ever you want to unshedule all the selectors being activated.

[self unscheduleAllSelectors];

:)

Play an MP3 in Adobe AIR/FLEX

Often in out applications we need to play sounds , so this code explains how to play, stop and resume an mp3 sound in Adobe AIR/FLEX.
What you have to do is to copy the following code and place it inside your “mx:Script” tag.
After that place three buttons for play, pause and stop and connect it to the three functions coded below.
Make sure that you have the sound file in your applications directory.


import adobe.utils.CustomActions;
import air.net.URLMonitor;
import flash.media.Sound;
import flash.media.ID3Info;
import flash.net.URLRequest;

var sound:Sound = new Sound(new URLRequest("app:/my_sound.mp3"));
var my_channel:SoundChannel;
var pausePos:int = 0;
[Bindable]
private function play():void
{
       my_channel= sound.play();
}
private function stop():void
{
      pausePosition = my_channel.position;
      my_channel.stop();
}
private function resume():void
{
       my_channel = sound.play(pausePos);
}

Please leave your valuable comments.

How to load a PDF in Titanium?

Loading a PDF file in Titanium may be sometimes our requirement for an application. For loading a PDF we need to have a webview inside a scrollview so that it is scrollable also. Take a look at this simple example.

/** creating a window **/
var window = Titanium.UI.createWindow{};
/** creating a webview **/
var my_webview = Titanium.UI.createWebView({     url :'my_pdf.pdf'      //specify the PDF path.....});
/** creating a scrollview **/var my_scrollView = Titanium.UI.createScrollableView({     views:[my_webview]   // placing the webview inside the scrollview...});
window.add(scrollView);

Please leave your valuable comments if this post was useful…..

Load a webpage in Adobe AIR

This example shows how to load a webpage inside Adobe AIR,
For this first you have to place an HTML control in your design for loading the html content.
Create an page “index.html” inside the application directory of your current project and add some Html content to it.
After that copy the following code to your source file.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
<mx:Script>
<![CDATA[
      private function init():void
      {
         this.stage.nativeWindow.maximize();    // maximizes your window.
         html.location="index.html";            // loads the html content in the html text area.
      }
]]>
</mx:Script>
<mx:HTML id="html"     width="100%" height="100%" />
</mx:WindowedApplication>

Please leave your comments on this post…….

Dynamically Load CSS in Adobe AIR/FLEX / Load css in Adobe AIR/FLEX using Class.

This example shows how to dynamically load css in Adobe AIR / FLEX.
Here in this example Panel id the tag name for the panel control. Drag a panel control to your design then copy the code to your source file. “myTabs” is the class for the CSS.




	Panel {
   borderColor:  #CBE0FF;
   border-style:solid;
   borderThickness: 1;
   borderThicknessLeft: 0;
   borderThicknessTop: 0;
   borderThicknessBottom: 0;
   borderThicknessRight: 0;
   cornerRadius: 4;
   highlightAlphas: 1, 0.49;
   headerColors: #0066ff, #ffffff;
   backgroundColor: #F5FAFF;
}
TitleWindow{
	borderColor:#CBE0FF;
   border-style:solid;
   borderThickness: 1;
   borderThicknessLeft: 0;
   borderThicknessTop: 0;
   borderThicknessBottom: 0;
   borderThicknessRight: 0;
   cornerRadius: 4;
   backgroundAlpha: 1;
   highlightAlphas: 1, 0.49;
   headerColors: #0066ff, #ffffff;
   backgroundColor: #F5FAFF;
   footerColors: #0099ff, #ffffff;
}

ComboBox
{
	cornerRadius: 4;
  	highlightAlphas: 0.52, 0.52;
	fillAlphas: 0, 1, 1, 1;
	fillColors: #0066ff, #ffffff, #ff9900, #eeeeee;
	borderColor: #cccccc;
	font-family:arial;
	font-size:11px;
	font-weight:normal;
	color:#000000;
}

ApplicationControlBar {
   highlightAlphas: 1, 0.42;
   fillAlphas: 0.78, 0.8;
   fillColors: #619ffc, #ffffff;
   backgroundAlpha: 1;
   cornerRadius: 1;
   shadowDistance: 1;
}
TabBar {
	tab-style-name: "myTabs";
	selected-tab-text-style-name: "mySelectedTabs";
    padding-left:0px;
	padding-right:0px;
	padding-top:0px;
	padding-bottom:0px;
	vertical-gap:0px;
	horizontal-gap:0px;
}
.myTabs {
   cornerRadius: 4;
   highlightAlphas: 0.30, 0;
   fillAlphas: 0.60, 0.40;
   /* fillColors: #c0dcf9, #e8f0f8; */
   fillColors: #95d0fe, #95d0fe;
   borderColor: #ffffff;
   border-thickness:4px;
   color: #0b333c;
   fontFamily: Arial;
   font-weight:bold;
   font-size:11px;
   backgroundColor: #f8d49d;
   padding-left:1;
   text-align:left;
   horizontal-gap:4px;
   vertical-align:middle;

}

.mySelectedTabs {
   textAlign: left;
   fontFamily: Arial;
   fontWeight: normal;
}
HBox{
 backgroundColor: #ffffff;
}


	
	
		
	
	
	
	
	
		
			
			
			
		
	
	
		
	
	
	
	
		
		
		
		
	
	
	
	
	
		
	
	
	
	


Client Side Form Validation – using JavaScript

Hi, JavaScript is mainly used for client side scripting. In client side scripting one of the thing which we are usually in need is Validation of Forms. We want to know the user , who is interacting with the form have already given the necessary details before submitting or saving etc. Here is a simple form validation example using JavaScript where the form is checked for a particular text field have entered or not. Here is the form code

First name:

It contains a Text field to enter first name and a button to save.
On clicking the Save button it will go for ‘validateForm()’ function and checks for user entry.

validateForm() code

[/css]
function validateForm()
{
var x=document.forms["trialForm"]["firstName"].value
if (x==null || x=="")
  {
  alert("Enter your first name before saving!");
  return false;
  }
}

This function checks for it & returns alert if it is not filled properly! :)

Using ButtonBar in Adobe AIR/FLEX, A simple Example

Hello……….

A button Bar is a convenient way to place your buttons in an application. It saves a lots of space in your application interface.
Take a look at the following example which shows how to use the ButtonBar. An itemClickEvent is attached to each button in the ButtonBar.
You can place as many buttons inside a button Bar.
Copy the following code to your MXML file and you are done…….
Happy Coding………..

<?xml version="1.0"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" >
    <mx:Script>
        <![CDATA[
            import mx.events.ItemClickEvent;

            private function clickHandler(event:ItemClickEvent):void {
                    myTA.text="Selected button index: " +
                    String(event.index) + "n" +
                    "Selected button label: " +
                    event.label;
            }
        ]]>
    </mx:Script>

    <mx:ToggleButtonBar  borderStyle="solid"  horizontalGap="5"  itemClick="clickHandler(event);"
    	    toggleOnClick="true"  selectedIndex="-1">
        <mx:dataProvider>
            <mx:String>Button1</mx:String>
            <mx:String>Button2</mx:String>
            <mx:String>Button3</mx:String>
            <mx:String>Button4</mx:String>
        </mx:dataProvider>
    </mx:ToggleButtonBar>
    <mx:TextArea id="myTA" width="250" height="100"/>
</mx:WindowedApplication>

Please leave your comments on this post.

How to load a URL in Objective C or Cocoa in iPhone?/ Open Safari in Objective C

This code snippet helps you to open a webpage in Safari.
Code uses openURL to load the webpage in the web browser.
Write this function as an action to a button………

- ( IBAction ) loadWebPageInSafari : ( id ) sender
{
          NSURL *my_URL = [NSURL URLWithString:[Your_URL stringValue]];
          if ( [ [NSWorkspace sharedWorkspace] openURL : my_URL ] ){
                   NSLog(@” URL Loaded................”);
         }else{
                   NSLog(@" Failed to Load URL.....");
         }
}

Using Arrays in JavaScript – Basics

Hi…

We all know, Arrays are nothing but variables which can hold all your variable values with a single name.

Let’s see some basic operations of Arrays in JavaScript.

To Create a New Array. Use the following code.

 var myArray = new Array();

This code of line created a new Array object called myArray.

Adding Elements to myArray

myArray[0]= "you";
myArray[1] = "me";
myArray[2] = "we";

or

var myArray=new Array("you","me","we"); 

or

var myArray=["you","me","we"];

Accessing Array Elements

document.write(myArray[0]);

It will print ‘you’!

:)

How to get a selected Item from a spinner in ANDROID?

We have come across this issue many times during programming to get a selected item in your combobox.
ANDROID has built in functions to get the selected item from a spinner.
Take a look at the snippet.
Here my_spinner id the spinner variable and using getSelectedItem() which will return an object and by using toString() I am converting it to human readable string…

my_spinner.getSelectedItem().toString();

Please leave your valuable comments…..