30 November 2014

Working Bullet Shooting Java Game Source Code

Below is the working code for Bullet Shooting Game developed using Java.
This game project includes 5 java files:





  • Window.java
package balloone_Shooting;
import javax.swing.JFrame;
public class Window {
/**
 * @param args
 */
public static void main(String[] args) {
Combine c = new Combine();
JFrame f = new JFrame("Cloud Shooting");
f.add(c);
f.setResizable(false);
f.setSize(800,700);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
}


  • Paddle.java
package balloone_Shooting;
import java.awt.Image;
import javax.swing.ImageIcon;

public class Paddle {
private int x, y;
private boolean left = false, right = false;;

Image volcano;
ImageIcon big = new ImageIcon(this.getClass()
.getResource("volcano_big.png"));
ImageIcon small = new ImageIcon(this.getClass().getResource(
"volcano_small.png"));
public Paddle() {
x = 395;
y = 630;
volcano = small.getImage();
}
public void setLeft(boolean left) {
this.left = left;
}
public void setRight(boolean right) {
this.right = right;
}
public boolean getLeft() {
return left;
}
public boolean getRight() {
return right;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return volcano;
}
public void left() {
x -= 2;
if (x <= 0)
x = 0;
}
public void right() {
x += 2;
if (x >= 706)
x = 706;
}
public void volcano_Pressed() {
y = 630;
volcano = small.getImage();
}
public void volcano_Release() {
y = 620;
volcano = big.getImage();
}
}

  • FireBall.java
package balloone_Shooting;

import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;

public class FireBall {

private int x, y;
private Image image;
boolean visible;
private int width, height;
private int dy;

public FireBall(int x) {
dy = 20;
y = 605;
ImageIcon ii = new ImageIcon(this.getClass()
.getResource("fireball.png"));
image = ii.getImage();
visible = true;
width = image.getWidth(null);
height = image.getHeight(null);
this.x = x;
}

public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void move() {
y = y - dy;
}
}

  • Cloudball.java
package balloone_Shooting;

import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;

public class Cloudball {
private int x, y, width, height;
private Image img;

public Cloudball(int x) {
ImageIcon ic = new ImageIcon(this.getClass().getResource(
"cloudball.png"));
img = ic.getImage();
this.x = x;
y = 0;
width = img.getWidth(null);
height = img.getHeight(null);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move() {
y++;
}
public Image getImage()
{
return img;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
}



    • Combine.java
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Random;
    import javax.swing.*;

    public class Combine extends JPanel implements ActionListener {
    Image back_Ground;
    Timer timer;
    Paddle paddle;
    ArrayList<FireBall> fireballs_array;
    ArrayList<Cloudball> cloud_array;
    FireBall fireBall;
    private boolean fire;

    public boolean isFire() {
    return fire;
    }
    public void setFire(boolean fire) {
    this.fire = fire;
    }
    public Combine() {
    addKeyListener(new Action());
    ImageIcon ii = new ImageIcon(this.getClass().getResource(
    "skybackground.png"));
    fireballs_array = new ArrayList<FireBall>();
    cloud_array = new ArrayList<Cloudball>();

    paddle = new Paddle();
    setFocusable(true);
    back_Ground = ii.getImage();
    timer = new Timer(70, this);
    timer.start();
    Thread startCloud = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    cloudBalls();
    Thread.sleep(1000 * 2);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    startCloud.start();
    Thread startFire = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    //System.out.println("fire " + fire);
    if (fire == true) {
    fire();
    }
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    startFire.start();
    Thread movePaddle = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    if (paddle.getLeft() == true) {
    paddle.left();
    }
    if (paddle.getRight() == true) {
    paddle.right();
    }
    Thread.sleep(9);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    movePaddle.start();
    }
    public void actionPerformed(ActionEvent arg0) {
    for (int k = 0; k < fireballs_array.size(); k++) {
    fireballs_array.get(k).move();
    if (fireballs_array.get(k).getY() < 1) {
    fireballs_array.remove(k);
    }
    }
    for (int i = 0; i < cloud_array.size(); i++) {
    cloud_array.get(i).move();
    if (cloud_array.get(i).getY() > 600) {
    cloud_array.remove(i);
    }
    }
    Thread collide = new Thread(new Runnable() {
    public void run() {
    collision();
    }
    });
    collide.start();
    repaint();
    }
    public void paintComponent(Graphics g) {
    g.drawImage(back_Ground, 0, 0, null);
    g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(), null);
    if (!cloud_array.isEmpty()) {
    for (int i = 0; i < cloud_array.size(); i++) {
    g.drawImage(cloud_array.get(i).getImage(), cloud_array.get(i)
    .getX(), cloud_array.get(i).getY(), null);
    }
    }
    if (!fireballs_array.isEmpty()) {
    for (int k = 0; k < fireballs_array.size(); k++) {
    g.drawImage(fireballs_array.get(k).getImage(), fireballs_array
    .get(k).getX(), fireballs_array.get(k).getY(), null);
    }
    }
    }
    public void cloudBalls() {
    Random rn = new Random();
    int ran = rn.nextInt(730);
    Cloudball ball = new Cloudball(ran);
    cloud_array.add(ball);
    }
    public void fire() {
    fireBall = new FireBall(paddle.getX() + 35);
    // fireBall.setY(20);
    fireballs_array.add(fireBall);
    }
    public void collision() {
    for (int k = 0; k < fireballs_array.size(); k++) {
    for (int j = 0; j < cloud_array.size(); j++) {
    Rectangle r1;
    if(!fireballs_array.isEmpty()){
     r1 = fireballs_array.get(k).getBounds();
    Rectangle r2 = cloud_array.get(j).getBounds();
    if (r1.intersects(r2)) {
    fireballs_array.remove(k);
    cloud_array.remove(j);
    }
    }
    }
    }
    }
    private class Action extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
    paddle.volcano_Pressed();
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_SPACE) {
    fire = true;
    }
    if (keyCode == KeyEvent.VK_LEFT) {
    paddle.setLeft(true);
    }
    if (keyCode == KeyEvent.VK_RIGHT) {
    paddle.setRight(true);
    }
    }
    public void keyReleased(KeyEvent e) {
    paddle.volcano_Release();
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    fire = false;
    }
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    paddle.setLeft(false);
    }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    paddle.setRight(false);
    }
    }
    }
    }

    13 July 2014

    KeyListener example in java

    KeyListener Example


    /*
    *its the first class
    *save is as Car.java
    /*
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.KeyEvent;

    public class Car {

    static int CARWIDTH = 40;
    static int CARLENGTH = 70;
    int x = Game.WIDTH/2 - CARWIDTH/2;
    int y = Game.HEIGHT - 105;
    int dx = 0;
    int dy = 0;
    private Game game;

    public Car(Game game){
    this.game = game;
    }

    public void paint(Graphics2D g2d){
    g2d.setColor(Color.blue);
    g2d.fillRect(x, y, CARWIDTH, CARLENGTH);
    }

    public void move(){

    if(x+dx > 0 && x+dx < Game.WIDTH-56) x = x+dx;
    if(y+dy > 0 && y+dy < Game.HEIGHT-105) y = y+dy;

    }

    public void keyPressed(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_LEFT) dx = -1;
    if(e.getKeyCode() == KeyEvent.VK_RIGHT) dx = 1;
    if(e.getKeyCode() == KeyEvent.VK_UP) dy = -1;
    if(e.getKeyCode() == KeyEvent.VK_DOWN) dy = 1;
    }

    public void keyReleased(){
    dx = 0;
    dy = 0;
    }

    }
    //////////////EnD of First Class////////////////

    /*
    *its the SECOND class
    *save is as Game.java
    /*


    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    @SuppressWarnings("serial")
    public class Game extends JPanel{

    static int WIDTH = 500;
    static int HEIGHT = 700;
    Car car = new Car(this);


    public Game(){
    addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
    car.keyReleased();

    }

    @Override
    public void keyPressed(KeyEvent e) {
    car.keyPressed(e);

    }
    });
    setFocusable(true);
    }

    private void move(){
    car.move();
    }

    public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    car.paint(g2d);
    }



    public static void main(String args[]) throws InterruptedException{
    Game game = new Game();
    JFrame frame = new JFrame("Car Game");
    frame.add(game);
    frame.getContentPane().setBackground(Color.white);
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    while(true){
    game.move();
    game.repaint();
    Thread.sleep(1);
    }
    }


    }
    ////////////////////EnD of Second Class////////////////////////////

    How to paddle in brick breaker

    Simple Paddle in Brick Breaker




    Code for simple paddle in java brick breaker game

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    import test1.BallBreaker;



    public class Bat extends JPanel{


    private int x = 140;

    private int y = 240;

    int width = 30;

    int height = 10;
    public Bat(){
    addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent evt) {
    moveIt(evt);
    }
    });
    setFocusable(true);
    }

    public void paint(Graphics g)
    {
    /*
    *
    * As we are extending JPanel,
    * we need to paint background with some color first
    * Note: if we extend Canvas class than we need not
    * paint back ground. we can directly draw peddle
    */
    g.setColor(Color.LIGHT_GRAY);//paint background with light gray
    g.fillRect(0, 0, 350, 450);//screen dimensions
    g.setColor(Color.blue);//change color value from gray to blue
    g.drawRect(x, y, width, height);
    g.fillRect(x, y, width, height);//fill blue color to paddle

    /*
    * you can uncomment below two lines to see styles of peddle
    */
    // g.fill3DRect(x, y+40, width, height, false);

    // g.fill3DRect(x, y+80, width, height, true);
    }
    protected void moveIt(KeyEvent evt) {////finds which key is pressed eighter left of right
    if (x < 3) {
    x = 3;
    } else if (x > 290) {
    x = 290;
    }

    switch (evt.getKeyCode()) {
    case KeyEvent.VK_LEFT:
    x -= 5;
    break;
    case KeyEvent.VK_RIGHT:
    x += 5;
    break;
    }

    repaint();
    }

    //public int getX() {
    // return x;
    //}
    //
    //public void setX(int x) {
    // this.x = x;
    //}
    //
    //public int getY() {
    // return y;
    //}
    //
    //public void setY(int y) {
    // this.y = y;
    //}

    public static void main(String[] args) {
    Bat bat = new Bat();
    JFrame jf = new JFrame("game");
    jf.add(bat);
    jf.setSize(350,450);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }


    }

    25 April 2014

    draw text in canvas using edittext

    draw text in canvas using edittext

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="packagename.MainActivity">

    <intraction.arrow.app.DrawView
        android:id="@+id/drawView"
        android:layout_width="fill_parent"
        android:layout_height="200dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:hint="Enter your Text"
            android:focusable="true"
            android:layout_below="@+id/drawView"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save Image"
            android:id="@+id/button"
            android:layout_below="@+id/editText"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />


    </RelativeLayout>




    MainActivity.java

    package packagename;


    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;

    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;



    public class MainActivity extends ActionBarActivity {

        Communicator communicator;
    //ListView listView;
        EditText editText;
        Button saveButton;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //listView = (ListView) findViewById(R.id.listView);
            //NetworkConfig config = new NetworkConfig("http://arrowgifts.com/mobile/mobile_home");

            //drawView = new DrawView(this);
            //drawView = (DrawView) findViewById(R.id.drawView);
            communicator = (Communicator)findViewById(R.id.drawView);
            //setContentView(drawView);
           // save();
            saveButton = (Button) findViewById(R.id.button);
            saveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    communicator.saveImage();
                }
            });
            editText = (EditText) findViewById(R.id.editText);
    editText.addTextChangedListener( new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
    communicator.writeText(editText.getText().toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
         
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

    /**
     * Communicator
     * **/
    public interface Communicator{
        public void writeText(String string);
        public void saveImage();
    }



    }
    //...................................\\


    DrawView.java

    package packagename;


    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;


    import android.util.AttributeSet;

    import android.view.View;



    /**
     * Created by sravan on 4/22/2014.
     */
    public class DrawView extends View implements MainActivity.Communicator {
        Bitmap bitmap;
    Bitmap newBitmap;

    //        public DrawView(Context context) {
    //            this(context,null);
    //        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.templer);
    //        newBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth()-100,bitmap.getHeight()-100);
    //
    //
    //    }

        public DrawView(Context context, AttributeSet attrs) {

            super(context, attrs);
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.templer);
            newBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth()-100,bitmap.getHeight()-100);
        }

    //    public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {
    //        super(context, attrs, defStyleAttr);
    //    }







        @Override
        protected void onDraw(Canvas canvas) {

            super.onDraw(canvas);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.RED);
            paint.setTextSize(50);
            paint.setStyle(Paint.Style.FILL);


            canvas.drawBitmap(newBitmap, 0, 0, null);

            canvas.drawText(textToBeWritten, 10, 50, paint);
            setDrawingCacheEnabled(true);

        }

    private String textToBeWritten ="Enter Text" ;
        @Override
        public void writeText(String string) {
            textToBeWritten = string;
            invalidate();
        }

        @Override
        public void saveImage() {
            SaveFile saveFile = new SaveFile();
            saveFile.save(getDrawingCache());
        }
    }



    SaveFile.java


    package packagename;

    import android.graphics.Bitmap;
    import android.os.Environment;
    import android.util.Log;

    import java.io.File;
    import java.io.FileOutputStream;

    /**
     * Created by sravan on 4/23/2014.
     */
    public class SaveFile {

        //Bitmap bitmap;// = getDrawingCache();
        public void save(Bitmap bitmap) {


            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/saved_images");
            myDir.mkdirs();

            String fname = "Image.jpg";
            File file = new File (myDir, fname);
            if (file.exists ()) file.delete ();
            try {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                Log.i("Success", root + "/saved_images");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //..............................//


    Tested in Android 4.2.2. API Level 19, and working fine.

    10 April 2014

    Key Down events in wp7

    <TextBox Name="hrTextBox" MaxLength="1" Text="0"  KeyDown="hrTextBox_KeyDown" TextAlignment="Center" InputScope="Number"/>


    Add this in your construcor to allow only numbers in text box


                InputScope scope = new InputScope();
                InputScopeName name = new InputScopeName();

                name.NameValue = InputScopeNameValue.Number;
                scope.Names.Add(name);

             

                minTextBox.InputScope = scope;

     private void hrTextBox_KeyDown(object sender, KeyEventArgs e)
            {
                switch (e.Key)
                {
                    case Key.D0:
                    case Key.D1:
                    case Key.D2:
                    case Key.D3:
                    case Key.D4:
                    case Key.Back:
                    case Key.Delete:
                        break;
                    default: e.Handled = true;
                        return;
                }
            }


         
            private void minTextBox_KeyDown(object sender, KeyEventArgs e)
            {
                if (minTextBox.Text != "")
                {
                    if (int.Parse(minTextBox.Text) >= 6)
                    {
                        switch (e.Key)
                        {
                            case Key.Back:
                            case Key.Delete:
                                break;
                            default: e.Handled = true;
                                return;
                        }
                    }
                }

    09 April 2014

    Play shoutcast stream in Windows phone 7



    Here are the steps to play shoutcast stream in wp7.

    1) Download the open source project from here
    2) extract the file and check the folders in the project
    you will find "Bin" and "src" folders. open "src" folder
    3) Now you will find following packages:-
    Shoutcast.Sample
    Shoutcast.Sample.Phone
    Shoutcast.Sample.Phone.Background
    Shoutcast.Sample.Phone.Background.PlaybackAgent
    Silverlight.Media.ShoutCast
    4) Add Shoutcast.Sample.Phone.Background.PlaybackAgent, and
    Silverlight.Media.ShoutCast in to your project
    5) Now go to your main project(UI project) right click on Referencts and select add Reference
    6) Select "Solution" in right pannel there you will find projects (Shoutcast.Sample.Phone.Background.Playback
    Silverlight.Media.ShoutCast.Phone)
    7) Check the box Shoutcast.Sample.Phone.Background.Playback project and click "Ok"
    (Note:- if you dont want to play background audio than you can add only Silverlight.Media.ShoutCast.Phone to your project)
    8) Now go to Properties folder on top of the References go to WMAppManifest.xml right click on that and open with "xml(Text) editor"(this is for vs 2012)
    9) add the following lines below </Capabilities>
        <Tasks>
          <DefaultTask Name="_default" NavigationPage="YourMainPage.xaml" />
          <ExtendedTask Name="BackgroundTask">
            <BackgroundServiceAgent Specifier="AudioPlayerAgent" Name="Shoutcast.Sample.Phone.Background.PlaybackAgent" Source="Shoutcast.Sample.Phone.Background.PlaybackAgent" Type="Shoutcast.Sample.Phone.Background.Playback.AudioPlayer" />
            <BackgroundServiceAgent Specifier="AudioStreamingAgent" Name="Shoutcast.Sample.Phone.Background.StreamAgent" Source="Shoutcast.Sample.Phone.Background.PlaybackAgent" Type="Shoutcast.Sample.Phone.Background.Playback.AudioTrackStreamer" />
          </ExtendedTask>
        </Tasks>
    10) now rebuild your entire solution check to see if any errors in your build. if no errors found then your back ground audio should work


    -Please comment for any quires. 

    01 April 2014

    VisualTreeHelper in wp7




            /// <summary>
            /// Finds a Child of a given item in the visual tree.
            /// </summary>
            /// <param name="parent">A direct parent of the queried item.</param>
            /// <typeparam name="T">The type of the queried item.</typeparam>
            /// <param name="childName">x:Name or Name of child. </param>
            /// <returns>The first parent item that matches the submitted type parameter.
            /// If not matching item can be found,
            /// a null parent is being returned.</returns>
            public static T FindChild<T>(DependencyObject parent, string childName)
               where T : DependencyObject
            {
                // Confirm parent and childName are valid.
                if (parent == null) return null;

                T foundChild = null;

                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < childrenCount; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    // If the child is not of the request child type child
                    T childType = child as T;
                    if (childType == null)
                    {
                        // recursively drill down the tree
                        foundChild = FindChild<T>(child, childName);

                        // If the child is found, break so we do not overwrite the found child.
                        if (foundChild != null) break;
                    }
                    else if (!string.IsNullOrEmpty(childName))
                    {
                        var frameworkElement = child as FrameworkElement;
                        // If the child's name is set for search
                        if (frameworkElement != null && frameworkElement.Name == childName)
                        {
                            // if the child's name is of the request name
                            foundChild = (T)child;
                            break;
                        }
                    }
                    else
                    {
                        // child element found.
                        foundChild = (T)child;
                        break;
                    }
                }
                return foundChild;
            }
         

    31 March 2014

    How to install Java on windows

    How to Install Java in Windows 7

    Java

    1. First check whether Java is installed or not in your system.
    • Open MyComputer > Local Disk C: > Program Files > Common Files  and see if a folder named "Java" is present.
    • If the "Java" folder is present then you need to check if "environment variables path" is set or not
    •  If java dose not exist then you need to download  java jdk from Oracle website. Accept license agreement before downloading. Select your os(32 or 64-bit) and download. 
    • Java is open source software. It provides free download to the users and developers.
    • There are two kinds of java packages, one is jdk :- Java Development Kit, and other is jre:- Java Runtime Envirement
    • JDK:- It is used by developers to develop java based programmes like standalone(Disktop) and server applications.
    • JRE:- Is used to by the operating system to run java applications in the local computer.
    • JRE will convert java bite code instructions to system understandable Machine code which is executed by the system.
    • To download java for free click below link

    Download and install java jdk. 
    • Install Java from the download.
    • Now Installation is successfull but its not yet over,  you need to set environment variables
    • Open command prompt and type javac in command line.
    • Then it shows 'Javac' is not recognized as an internal or external command.checking-for-java
    • You need to set environment variable path to avoid this java error.
    • In order to set path right click on Computer and click properties there you can find advanced system settings on left side pannel of the window.
      MyComputer-propertiesAdvanced-System-Settings

    • Now click on Advanced tab.
    • Under Advanced tab click environment variables button as shown below.



    System-Properties

    • On clicking the button you find a Environment Variable popup.
    •  Now under User variables click "New" and set 
    • variable name : PATH and variable value : C:\Program Files\Java\jdk1.7.0\bin .
    • Then click OK.
    • Now again open command prompt to check if java is installed or not.
    • To do this you need to type javac on the command line It will show all java commands as shown in below image.It means that java has been successfully installed on your computer.


    check-for-java

    • Now you can use notepad to write the code or download any IDE(Integrated Development Environment) and start programming(Starting with eclipse).
           Check this: Java programmes for beginners

    14 March 2014

    Change Background Image on pressed ListBox

    <Grid x:Name="LayoutRoot" Background="Transparent">
            <!--toolkit:TiltEffect.IsTiltEnabled="True"-->
            <ListBox x:Name="Channel_List" SelectionChanged="Listbox1_SelectionChanged" >
             
                <ListBox.ItemTemplate>
                    <DataTemplate>
                     
                        <ListBoxItem >
                            <StackPanel Width="490" MouseLeave="StackPanel_MouseLeave"  MouseLeftButtonDown="StackPanel_MouseLeftButtonDown" MouseLeftButtonUp="StackPanel_MouseLeftButtonUp">
                                <StackPanel.Background>
                                    <ImageBrush ImageSource="/Assets/Images/channel-bg-unsel.png"/>
                                </StackPanel.Background>
                                <Image Source="{Binding Image}" />
                                <TextBlock Text="{Binding StationName}" FontFamily="Segoe Print" />
                            </StackPanel>
                        </ListBoxItem>
                     
                    </DataTemplate>
                </ListBox.ItemTemplate>
             
            </ListBox>

         
         
        </Grid>


    /////handle click events in code behind..



    private void StackPanel_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                var obj = (sender as StackPanel);
                ImageSource img = new BitmapImage(new Uri("/Assets/Images/channel-bg-sel.png", UriKind.Relative));
               ImageBrush ig = new ImageBrush();
               ig.ImageSource = img;
               obj.Background = ig;
                //obj.Background =
            }

            private void StackPanel_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                var obj = (sender as StackPanel);
                ImageSource img = new BitmapImage(new Uri("/Assets/Images/channel-bg-unsel.png", UriKind.Relative));
                ImageBrush ig = new ImageBrush();
                ig.ImageSource = img;
                obj.Background = ig;
            }

            private void StackPanel_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
            {
                var obj = (sender as StackPanel);
                ImageSource img = new BitmapImage(new Uri("/Assets/Images/channel-bg-unsel.png", UriKind.Relative));
                ImageBrush ig = new ImageBrush();
                ig.ImageSource = img;
                obj.Background = ig;
            }









    selectedSelected-background-image

    unselectedSelected-background-image

    12 March 2014

    WP7 Identity of the caller.

    unable to determine application identity of the caller. settings class

    or


    Exception while using IsolatedStorageSettings:
    System.IO.IsolatedStorage.IsolatedStorageException: Unable to determine
    application Identity of the caller.
     at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedScope
    scope,Type appEvidenceType)
     at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedScope
    scope,Type applicationEvidenceType)
     at System.Io.IsolatedStorage.IsolatedStorageSettings..ctor(boolean
    useSiteSettings)
     at System.IO.IsolatedStorage.IsolatedStorageSettings.get_ApplicationSettings()
     at ManasutoApp.AppSettings..ctor() in


    Try this code in your settings class.

    if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
                    {
                        settings = IsolatedStorageSettings.ApplicationSettings;
                    }


    "check if the code is running in (visual studio or blend) using DesignerProperties.IsInDesignTool since accessing IsolatedStorageSettings in Visual Studio or Expression Blend is invalid."

    I found this from StackOverFlow ..





    Specified argument was out of the range of valid values. wp7.

    for this you need to lode the settings class in Loded event.
    public partial class Page2 : UserControl
    public Page2(){
      Loaded += ChannelsPage_Loaded;
             
            }

            void ChannelsPage_Loaded(object sender, RoutedEventArgs e)
            {
                appSettings = new AppSettings();
                this.isolatedSettings(); // here you are calling method that uses isolated class

                var deviceId = DeviceExtendedProperties.GetValue("DeviceUniqueId"); // devide id of your Wp7
                byte[] bID = (byte[])deviceId;
                string deviceID = Convert.ToBase64String(bID);
            }


    if possible instantiate "settings" Class as


    if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
                    {
                        settings = AppSettings();// where you lode entire data from isolated storage
                    }

    25 February 2014

    Arraigning Bricks In Our Game

    Arrange-Bricks






    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.util.ArrayList;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class Bricks extends JPanel implements Runnable {

     // variables declaration for brick...............................
        //starting position of the bricks
     int brickx = 85;
     int bricky = 50;

     //You can specify length and breadth of the bricks here
     int brickBreadth = 50;
     int brickHeight = 40;
     // variables declaration for brick...............................
     // ===============================================================

     private static final String[] LEVELS_ONE = new String[] {
      "WWWWW",
      "W   W",
      "W W W",
      "W   W",
      "WWWWW"
      };
     private static final String[] LEVELS_TWO = new String[] {
      "WWWWW",
      "     ",
      "W W W",
      "     ",
      "WWWWW"
      };

     ArrayList<Rectangle> Brick = new ArrayList<Rectangle>();
     Thread t;

     Bricks() {

      setFocusable(true);
      t = new Thread(this);
      t.start();
     }

     public static void main(String[] args) {
      JFrame frame = new JFrame();
      Bricks game = new Bricks();
      JButton restart = new JButton("start");
      // JLabel lbl_startGame = new JLabel("Start Game", JLabel.LEFT);

      frame.setSize(350, 450);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.add(game);

      frame.add(restart, BorderLayout.SOUTH);
      frame.setLocationRelativeTo(null);
      frame.setResizable(false);
      frame.setVisible(true);

     }

     public void paint(Graphics g) {
      g.setColor(Color.LIGHT_GRAY);
      g.fillRect(0, 0, 350, 450);
      g.setColor(Color.blue);

      g.setColor(Color.green);
      g.setColor(Color.GRAY);
      g.fillRect(0, 251, 450, 200);
      g.setColor(Color.red);
      g.drawRect(0, 0, 343, 250);
      for (int i = 0; i < Brick.size(); i++) {
       if (Brick.get(i) != null) {
        g.fill3DRect(Brick.get(i).x, Brick.get(i).y,
          Brick.get(i).width, Brick.get(i).height, true);
       }
      }

     }

     int brickscount;

     public void run() {

      int xaxis = brickx;
      int yaxis = bricky;

      for (int row = 0; row < LEVELS_ONE.length; row++) {
       for (int col = 0; col < LEVELS_ONE[row].length(); col++) {

        if (LEVELS_ONE[row].charAt(col) == 'W') {

         Brick.add(new Rectangle(xaxis, yaxis, brickBreadth, brickHeight));
         xaxis += (brickBreadth+1);

        }
        if (LEVELS_ONE[row].charAt(col) == ' ') {
         xaxis += (brickBreadth+1);

        }

       }
       yaxis += (brickHeight+2);
       xaxis = brickx;
      }

     }// while loop ends here

    }

    Click here for Breaking Bricks Game Code

    Also see Bullet shooting game using Java.

    Multiple windows in any android device.

    Multitasking

    • Defined as the ability to perform many tasks at same time.
    Now a days almost all phones can do multitasking.
    All android phones support multitasking, this is done by placing the active tasks in a queue on ram so that they can be switched any time. But at a given time only one task can be done and cannot work on multiple tasks at same time.
    Android platform offers multiple windows applications to work on multiple applications at same time. Here are some applications which help multi window tasking.

    Floating Apps(Multitasking)

    Floating-Apps
    • You can turn home screen widgets or any URL in to floating window using this application. 
    • Windows can be minimized or resized or moved. 
    • Many floating apps are available by default. 
    • Works on any android phone and tablet. 


    Available floating apps:  

    Floating Applications Floating Active windows Floating Launcher
    Floating Add bookmark Floating Bookmarks Floating Search Google
    Floating Browser Floating Calculator Floating Search Wikipedia
    Floating Dialer Floating Flashlight Floating Stopwatch
    Floating System information Floating Video player Floating Add contact
    Floating Countdown Floating Facebook Floating File browser
    Floating Google plus Floating Image viewer Floating Music player
    Floating Notes Floating PDF viewer Floating Task Killer
    Floating Translate Floating Twitter Floating Vimeo
    Floating Wifi manager Floating Youtube

     Or create your own floating apps from home screen widgets or URLs!

    Link to download Floating Apps  DOWNLOAD

    Tiny Apps(Floating)

    Tiny-apps-floating
    • Tiny Apps is a package of 7 useful floating apps that stay on top of all other apps. All windows can be moved, resized and docked to the left side of your screen to hide and show windows quickly. Use your volume buttons to change the transparency of each window!
    Tiny Apps Pro enables the following features:
    - dock windows to the left side of your screen
    - adjust a window's transparency by using your volume buttons
    - 2 additional Tiny Apps: widgets and browser
    You can run several windows of the same Tiny App.

    Link to download Floating Apps  DOWNLOAD

    22 February 2014

    History of Android

    History-of-android


    • Android is an opensource operating system based on the Linux kernel and designed primarily for touchscreen mobile devices.
    • Initially developed by Android, Inc., which Google backed financially and later bought in 2005.
    Google-Android

    • Unveiled in 2007 
    • The first publicly available smartphone running Android, the HTC Dream, was released on October 22, 2008

    First-Android-SmartPhone-HTC-Dream

    • Android Evolution;


    Android-Evolution
    • Android 0.9 is the first version(beta) and has no name.
    • Version 1.0 is named as Apple pie, and Version 1.1 as Banana Bread

    21 February 2014

    Play Lyrics in Windows Media Player

    Windows media player can not only play songs but also display lyrics in synchronization with the song being played. All you need is windows media player and a plugin(Lyrics Plugin) for playing lyrics.
    Click on download to get the plugin.
    Download-Lyrics-Plugin-for-windows-media-player


    Follow the slides shown;
    lyrics-plugin-download-page

    folder

    lyrics-plugin-installation

    lyrics-plugin-installation

    lyrics-plugin-installation

    lyrics-plugin-installation

    windows-media-player


    Select a song and click on play, player automatically searches for lyrics on web and displays them.
    lyrics-play







    Contact Form

    Name

    Email *

    Message *

    Smooth Graphics Java

    // Arrange Bricks in Game //java brick breaker game code without flickering // added game levels 1,2,3 in the game //java paddle ball ga...