Java TicTacToe


Hello people! Wow its been a while since I posted something here…! I must say I really miss writing stuff and I promise I wont get into a ‘writer’s block’ again. Hopefully :).. A helluva lot of things happened in the last two months and I’ve got loads to say. But in this post Im just gonna publish a small application that I wrote sometime ago. Its a TicTacToe game application. There’s not much to be learnt from this particular program but I really want to get outta this impasse and hence Im posting this today.

I actually wrote this code to show off some of the really cool features of Java to one of my friends who also wrote the same application in a “C++”-esque style. And btw that friend of mine even developed code for the computer player. But after completing his code he sadly realized the basic fact that you cannot win in TicTacToe if you play perfectly!! Hehe ūüėÄ So I did not venture into that area. Well to be honest, Im not really interested in writing AI apps. But I thought of adding Network Multiplayer functionality to this application since I love network programming. But unfortunately I havent had the time to do so.

Anywaiz the application works like this – the game is autostarted once launched and the status bar indicates which player’s turn its now and rest is just simple tictactoe! And at the end of the game the app is automatically reset.

Onto the code..


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;

/**
* TicTacToe Application
* @author Steve Robinson
* @version 1.0
*/

class TicTacToeFrame extends JFrame
{

	JButton [][] buttons= new JButton[3][3];
	JTextField statusBar;
	GamePanel panel;
	Integer turn;
	GameListener listener=new GameListener();
	Integer count;

	public TicTacToeFrame()
	{
		setLayout(new BorderLayout());

		panel=new GamePanel();
		add(panel,BorderLayout.CENTER);

		statusBar=new JTextField("Player1's Turn");
		statusBar.setEditable(false);
		add(statusBar,BorderLayout.SOUTH);

		setTitle("Tic Tac Toe!");
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(400,400,300,300);
	}

	class GamePanel extends JPanel
	{

		public GamePanel()
		{
			setLayout(new GridLayout(3,3));
			turn =1;
			count=0;
			for(int i=0;i<3;i++)
				for(int j=0;j<3;j++)			{
					buttons[i][j]=new JButton();
					buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
					buttons[i][j].putClientProperty("OWNER", null);
					buttons[i][j].addActionListener(listener);
					add(buttons[i][j]);
				}
		}
	}

	class GameListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			count++;
			JButton b=(JButton)e.getSource();
			Integer[]index=(Integer[]) b.getClientProperty("INDEX");

			//System.out.println(turn);	//turn       											//			//System.out.println("["+index[0]+"]"+"["+index[1]+"]");  							//
			b.putClientProperty("OWNER", turn);
			Icon ico=new ImageIcon(turn.toString()+".gif");
			b.setIcon(ico);
			b.setEnabled(false);
			boolean result=checkVictoryCondition(index);
			if(result)
			{
				JOptionPane.showMessageDialog(null, "Player "+turn.toString()+" Wins");
				initComponents();
			}
			else
			{
				if(turn==1)
				{
					turn=2;
					statusBar.setText("Player2's Turn");
				}
				else
				{
					turn=1;
					statusBar.setText("Player1's Turn");
				}
			}
			if(count==9)
			{
				JOptionPane.showMessageDialog(null, "Match is a draw!");
				initComponents();

			}

		}

		Integer getOwner(JButton b)
		{
			return (Integer)b.getClientProperty("OWNER");
		}

		//PrintButtonMap for Diagnostics
		void printbuttonMap(Integer [][]bMap)
		{
			for(int i=0;i				for(int j=0;j					System.out.print(bMap[i][j]+" ");
				System.out.println("");
			}
		}

		boolean checkVictoryCondition(Integer [] index)
		{
			/*Integer[][]buttonMap=new Integer[][] {
					{ getOwner(buttons[0][0]),getOwner(buttons[0][1]),getOwner(buttons[0][2])},
					{ getOwner(buttons[1][0]),getOwner(buttons[1][1]),getOwner(buttons[1][2])},
					{ getOwner(buttons[2][0]),getOwner(buttons[2][1]),getOwner(buttons[2][2])}
			};

			printbuttonMap(buttonMap); */

			Integer a=index[0];
			Integer b=index[1];
			int i;

			//check row
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[a][i])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check column
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[i][b])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check diagonal
			if((a==2&&b==2)||(a==0&&b==0)||(a==1&&b==1)||(a==0&&b==2)||(a==2&&b==0))
			{
				//left diagonal
				for(i=0;i					if(getOwner(buttons[i][i])!=getOwner(buttons[a][b]))
						break;
				if(i==3)
					return true;

				//right diagonal
				if((getOwner(buttons[0][2])==getOwner(buttons[a][b]))&&(getOwner(buttons[1][1])==getOwner(buttons[a][b]))&&(getOwner(buttons[2][0])==getOwner(buttons[a][b])))
					return true;

				}

			return false;

		}
	}

	void initComponents()
	{
		for(int i=0;i<3;i++)			
                         for(int j=0;j<3;j++)		{
				buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
				buttons[i][j].putClientProperty("OWNER",null);
				buttons[i][j].setIcon(null);
				buttons[i][j].setEnabled(true);
				turn=1;
				count=0;
				statusBar.setText("Player1's Turn");

			}
	}

}

class TicTacToe {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable(){
			public void run()
			{
				TicTacToeFrame frame=new TicTacToeFrame();
			}
		});

	}

}

The code is rather straightforward. Ive used two properties in the Buttons to store some information used for checking the winning condition. One is the “OWNER” property which indicates which user currently owns the square and the “INDEX” property which indicates the square’s index in the grid (ie [1,1], [1,2]… etc) Once any player clicks on a square, the OWNER property is updated and the victoryCondition is checked by using the OWNER properties of all the buttons. The rest of the code is self explanatory.

And adding keyboard support for the second player is a pretty easy job. As they say… “I leave that as an exercise”! Hahaha ūüėÄ Well I really hope I get some time so that I can add network functionality to this application.
Cheers,
Steve.

—–

I forgot to attach the image icon files that will be used by the application. You can download it from here…

 http://www.mediafire.com/?d7d93v2342dxind

Just extract the contents to the folder that contains the code. Thanks to my friend “Gur Png” for telling me about this.¬†
-Steve

Java Chat Application (Local Loop) V1.0


Hey guyz! Ive started a new project based on Java’s Network programming¬†capabilities¬†using RMI etc. The aim of the project is a to develop a full¬†fledged¬†chat application with a standalone server managing multiple clients. It will also have authentication features and account management also. I completed stage one of the project, which was to develop a working prototype of a simple client/server chat application which uses TCP/IP sockets to communicate within a local LAN. Initially I thought of adding RMI capability to this prototype but I felt it would add more complexity to this basic model. So I scrapped that plan. The reason why Im not gonna use TCP sockets for¬†subsequent¬†stages is because of the problem of ports being closed by routers and firewalls. Port forwarding can fix this but it still is a major headache for amateurs. Hence I decided to use RMI which has¬†tunneling¬†capabilities.

Anyway, Ive generated runnable jars for the Server and Client. Ive also included the source files so that you can look at it and may be learn a couple of things or modify it for your use.

Here is the package:

http://bit.ly/qlLrBG

Plans for stage 2:

Stage 2 of the project will incorporate RMI system into this prototype. I will be implementing the same system using RMI instead of TCP sockets and try running the application from remote systems. With some luck I should find some guys in my college who can lend me a hand in testing of the stage 2 application. It should be over by next week.

Regards,

Steve

Java 7 is Here!


Its finally here, the much awaited JAVA 7! After a wait of nearly 5 years, Oracle has released the latest installation of the Developer kit for the highly popular platform, Java! The new version still has the silly version number of 1.7.0 but is more popularly known as JDK 7 as in the case of JDK 6. JDK 7 brings some changes to the language features of Java and also some changes to the core systems and the VM as well. Id like to point out some of the new language features of Java 7 that could come in pretty handy.

Continue reading

Java Naming Conventions


I wanted to write this short post to help certain people who are having a hard time memorizing the Java API classes and Method names. As you know Java is a case sensitive language and to build Java programs you need to use a lot of Built-in API classes and methods. And beginners find it really hard to memorize the method names and Class names exactly without changing the case.

But actually you need not remember the case. It would be overkill to memorize it. But if you follow the Java Naming conventions, then you need not memorize the case of the methods and classes that you will be using. 99% of the classes in the JAVA API follow this naming convention. Only 1% of the names break this rule and that is also due to programmers forgetting to name it properly (its true!). ¬†So here goes…

1. Classes:

Class names always begin with a capital letter (eg. java.util.Scanner). And if there are mutiple words in the class name then each word must also begin with a capital letter (eg. java.util.GregorianCalendar). Also package names always start with lowercase characters (util, lang, io, etc). And if there are multiple words in the package name, then you need to use uppercase for all words except for the starting word. This naming method is popularly called as UpperCamelCase which is a type of CamelCase! Interfaces also use same convention.

class MyClass {
}

2. Objects/Variables:

Java Naming convention specifies that instances and other variables must start with lowercase and if there are multiple words in the name, then you need to use Uppercase for starting letters for the words except for the starting word. This is called as lowerCamelCase.

String myName;
MyClass myObject;
Scanner scannerObject = new Scanner(System.in);

3. Methods:

Methods in Java also follow the same lowerCamelCase convention like Objects and variables.

void myMethod() {
}
String myName = scannerObject.nextLine();

4. Constant Variables:

In Java constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’.

static final char END_OF_FILE = 'e';
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Well thats it. Again, all these conventions were created just to improve readability of code. So its your choice to use them or leave them. But if you do use them, your code will look professional. Java Compiler does expect you to use these conventions. But there are some languages where, the way you name your variables, indicates to the compiler what type of variable it is. For instance, in Ruby, for declaring a constant variable you have to use only Uppercase for entire name of the variable. Ruby compiler identifies constant variables in that way only! Thank God, Java is flexible!

Regards,

Steve Robinson.

Java Persistence API: a quick intro…


Hello Readers! After numerous requests from some of my friends I’ve decided to write a short article about the Java Persistence API. Object Oriented programming paradigm is the most popular and widely used model nowadays and it outclasses and outshines most other paradigms because of its ability to model real life entities seamlessly. But when it comes to developing medium-sized data oriented applications like a Students Database or an Employee Database, people just break the Object Oriented Model and link a DB Connection directly to the front-end GUI. But it isn’t a good programming practice. When I first started building small db oriented applications, me being a die-hard OOPS fan, was kinda worried about not using OOP model. ¬†A good programming practice is to have a Solid Object model and have a data store to hold data and then a GUI. So the model is basically like this,

But I stumbled into another problem. How do I link the objects and the database. Data in objects are stored differently than in a relational Data base. Relational database doesn’t support many OOPs concepts that are so crucial for our Object Model. So I thought of brewing my own classes to transfer data from a db to Objects and back. But I faced a lot of difficulties and stumbling blocks. Then came the break! I came across the Java Persistence stuff that allowed me to persist or save object’s data beyond the lifetime of the program. What that means is, you can now store Objects into data stores like Relational database or a XML file etc. without having to write complex code to convert the formats and to manage CRUD operations.

This small article will introduce you to this wonderful feature and you will be in a position to start implementing Persistence in your projects. I don’t want to go into complex topics in this article. So I decided to use ObjectDB Database. The advantage of using ObjectDB is that it doesn’t need complex configuration and mapping files that JPA normally needs. And we are going to use the popular Eclipse IDE. I’ll provide a simple example program that will store and manipulate Employee details (Name and Salary). Alright, lets start………!

Persistence service is provided by many providers and we are going to use ObjectDB’s implementation. So download their DB and API files.¬†Lets go through some basics now. And then we will see how to implement these to create a program…

I. The Entity Class: 

To use persistence, you need the class whose objects you’re gonna store in a database. There classes are called as Entity classes and they are same as POJOs (Plain Old Java Objects) except for some extra annotations. You need to define the fields inside this class that must be persisted (saved in db). An Entity class must have a “@Entity” annotation above the class. Now define all the fields and methods of the class. Voila we got ourselves an Entity class! Now you can add extra features to your entity class. For example you can indicate which field to use as a Primary key using the “@Id” annotation above that field. You can also make Object DB generate primary key value for the objects that you persist into the database using ¬† ¬† “@Id @GeneratedValue(strategy=GenerationType.AUTO) ” annotation. There are many more annotations and features and constructs. But we need not see about them now.

Here is the class that we will be using as the Entity Class….

package employeeDB;import javax.persistence.*;

@Entity
publicclass Employee {

    @Id String name;
    Double salary;

    public Employee()
    {

    }

    public Employee (String name, Double Salary)
    {
        this.name=name;
        this.salary=Salary;
    }

    publicvoid setSalary(Double Salary)
    {
        this.salary=Salary;
    }

    publicString toString()
    {
        return"Name: "+name+"\nSalary: "+salary ;
    }

}

As you can see we have the Entity class identified by @Entity annotation. Then we have employee name as the primary key. And you need to have  a default constructor without parameters in you entity class.

In other JPA implementations you may have to provide details about the entity classes in a¬†separate¬†XML file. But Object DB¬†doesn’t¬†require that.

II. Connecting to the Database

In JPA a database connection is represented by the EntityManager interface. In order to access and work with an ObjectDB database we need an EntityManager instance. We can obtain an instance of EntityManager using the EntityManagerFactory instance that is created using the static createEntityManagerFactory method of EntityManagerFactory class. You need to specify where to store the database file as an argument to the createEntityManagerFactory  method.

Example:

EntityManagerFactory emf=Persistence.createEntityManagerFactory("empDB.odb");
EntityManager em=emf.createEntityManager();

Now we have got an EntityManager that will connect our application to the database. Generally several EntityManagers are created in a program but only one EntityManagerfactory instance is created. Most JPA implementations require the XML Mapping file called as the “Persistence Unit” as the argument for creating EntityManagerFactory Instance. But Object DB has provisions for accepting only the location of the database. If the database already exists, it will be opened or else a new db will be created for us.

EntityManagerFactory and EntityManager can be closed as follows,

em.close();
emf.close();

Its a good practice to have a seperate EntityManager for each Class (that’s responsible for some db activity) or each Thread incase of a¬†Multi Threaded¬†Application. Now lets see how to make transactions with the Database….

III. Performing Transactions

For doing any operation with or on a database we must first start a transaction. Any operation can be performed only after a Transaction is started using an EntityManager. We can start a transaction using following call.

em.getTransaction().begin();

And now we can perform various transactions like create a new Record (Object), remove, update and retrieve data from the database. Before we can perform any of the CRUD operations, we need to add data to our database. In JPA inserting an object into a database is called as ‘persisting’ the object. This can be performed using the em.persist(Object) method. Now this object becomes ‘managed’ but that EntityManager (em). That means any changes made to that object will ¬†be reflected in its copy in the database file. And to remove any object from a database, we can use the em.remove(Object) method. ¬†We can¬†retrieve¬†an object from the database using the primary key of the object using the em.find(Class,primaryKeyValue) method. You need to pass an Class instance of the Entity class and the primary key to this method and it will return an “Object” which must be casted to the Entity Class. Finally after performing the transactions we have to end the transaction by using,

em.getTransaction().commit();

Only when the transaction is committed the changes made to the Objects in memory will be reflected on the Objects in the database file. The following code persists an Employee Object and then it Searches for an Employee Object and modifies it.

Employee emp1=new Employee ("Gugan",50000);

em.getTransaction().begin();

//Persist (store) emp1 object into Database
em.persist(emp1);

//Search for Gugan
Employee gugan=(Employee) em.find(Employee.class,"Gugan");
gugan.setSalary(100000);

em.getTransaction().commit();

We can also use SQL like queries called as the JPQL to perform the CRUD operations.

There are two types of queries in JPA. Normal queries and TypedQueries. Normal Queries are non-type safe queries. (i.e) The query does not know the type of Object its gonna retrieve or work with. But a TypedQuery is a type-safe query. For creating a typed query you need to specify the Type of class that will be used and also pass Class instance of the Class as parameter along with the Query String. TypedQueries are the standard way of working with Databases and hence we will use them only. They can be created using following Syntax,

TypedQuery  q=em.createQuery(queryString,EntityClass.class);

If your query will return only one Object or result, as in the case of finding number of Entries (count), then you can use the q.getSingleResult() method. On the other hand if your Query will return a collection of Objects, as in the case of retrieving a list of Employees from the database, you can use q.getResultList() method and it will return a List object of the type specified while creating the TypedQuery. The following piece of code will first find how many Employees are there and then it will retrieve all of the Employee objects from the database.

em.getTransaction().begin();

//find number of Employees
TypedQuery  count=em.createQuery("Select count(emp) from Employee emp",Employee.class);
System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n");

//Retrieve All Employee Objects in the database
TypedQuery  e=em.createQuery("Select emp from Employee emp", Employee.class);
List  employees=e.getResultList();

em.getTransaction().commit();

The JPQL is very similar to the SQL queries. The only difference is that you use Class names and Object names instead of the table names. JPQL also supports parameters in the queries. For eg. if you want to find the Employee with name “Steve” and if you know the name “Steve” only at runtime, you can use the following Query style.

String name=scannerObj.nextLine();
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e WHERE e.name = :name", Employee.class);
query.setParameter("name", name);
Employee emp=query.getSingleResult()

This replaces the “:name” parameter with the given “name” variable. Apart from these Queries, there are a lot of other queries. For a full tutorial on JPQL you can read ObjectDB manual about JPQL.

IV. Using Eclipse for ObjectDB JPA Implementation

Eclipse is the best IDE for Java AFAIK. So I recommend using Eclipse for developing your applications. Download the latest Eclipse Indigo from here. If you already have Eclipse Indigo or an older edition, then its perfectly fine. Create a new Java Project using File Menu. And in the new Project Dialog, enter a project name for your Project and select the directory in which you want to store your project and select Next. After pressing next you will be provided several options and now in this window select Libraries tab. And then select “Add External Jars” button which will open a new dialog. Now browse to the location where you extracted the ObjectDB API files and go to the bin folder within it and select the “objectdb.jar” file. Press open and the library will be added. Now press finish to Create your Project.

(If you can’t view the image properly click here…. Im breaking my head over these silly WordPress themes. None of them has a wide enough text Column)

Now that we have created our Project, we need to add classes to it. Now right click your project name on the Project Explorer pane on the left side of the Eclipse IDE window and select New -> Class. Now the New Class dialog will open up. In it, Enter the class name you want to create and then enter a package name as well. All other options need not be meddled with…! In our example program we are going to use two classes. One for the Employee Entity and the another one to house the main method and the key functionality of the application. Make sure that both classes are under same package. To view the created classes, expand your Project in the Project Explorer pane and from the list of nodes, expand src and youll see your package there. Expand it and you will see the classes.

V. Example Program

Now that you have some basic idea about JPA, Ill present an Example console application, that will store, modify and delete Employees from a Database… If you’ve read the above text, then you can easily follow the following program. I have provided comments wherever needed to make the program more clear.

Create a class called Employee using the method I told you in the above section, using employeeDB as your package name and paste the code of the Employee Entity class that I gave in section I of the tutorial.

Now create another class called Main under same package employeeDB and put following code in it.

package employeeDB;

import javax.persistence.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    /**
* Displays all Employees in the Database
*/
    private static void displayAll()
    {
        em.getTransaction().begin();
        TypedQuery  e=em.createQuery(displayAllQuery, Employee.class);
        List <Employee> employees=e.getResultList();
        if(employees.size()>0)
        {
            for(Employee temp:employees)
            {
                System.out.println(temp);
                System.out.println();
            }
            System.out.println(employees.size()+" Employee Records Available...!");
        }
        else
            System.out.println("Database is Empty!");
        em.getTransaction().commit();
    }

    /**
* Insets an Employee into the Database.
*/
    private static void insert()
    {
            System.out.print("Enter the number of Employees to be inserted: ");
            n=input.nextInt();
            em.getTransaction().begin();
            for(int i=0;i<n;i++) 
            { 

                System.out.println("Enter the details of Employee "+(i+1)+": ");
                System.out.print("Name: ");

                //I use BufferedReader to read String and hence I need to 
                // Catch the IOException that it may throw
                try
                {
                    name=bufferedReader.readLine();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                System.out.print("Salary: ");
                Salary=input.nextDouble();

                Employee emp=new Employee(name,Salary);
                em.persist(emp);                                //Store emp into Database
            }

        em.getTransaction().commit();

        System.out.println("\n"+n+" employee record(s) Created!\n");

        TypedQuery  count=em.createQuery(countQuery,Employee.class);
        System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n");
    }

    /**
* Deletes the specified Employee from the database
*@param name
*/
    private static void delete(String name)
    {
        em.getTransaction().begin();

        Employee e=(Employee) em.find(Employee.class, name);         //Find Object to be deleted
        em.remove(e);                                                //Delete the Employee from database

        System.out.printf("Employee %s removed from Database....",e.name);

        em.getTransaction().commit();

        //Display Number of Employees left
        TypedQuery  count=em.createQuery(countQuery,Employee.class);
        System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n");
    }

    /**
* Changes salary of the specified employee to passed salary
*@param name
*@param Salary
*/
    private static void modify(String name,Double Salary)
    {
        em.getTransaction().begin();
        Employee e=(Employee) em.find(Employee.class, name);  //Find Employee to be modified
        e.setSalary(Salary);                                  //Modify the salary
        em.getTransaction().commit();
        System.out.println("Modification Successful!\n");
    }

    public static void main(String arg[])
    {

        System.out.println("Welcome to the Employee Database System!\n\n");

        do{    

            System.out.print("Menu: \n 1. View DB\n2. Insert \n3. Delete \n4. Modify\n5. Exit\nEnter Choice...");
            int ch=input.nextInt();

            try{

                switch(ch)
                {

                case 1:
                    displayAll();
                    break;

                case 2:
                    insert();
                    break;

                case 3:
                    System.out.print("Name of Employee to be Deleted2: ");
                    name=bufferedReader.readLine();
                    delete(name);
                    break;

                case 4:
                    System.out.print("Name of Employee to be Modified: ");
                    name=bufferedReader.readLine();
                    System.out.print("New Salary: ");
                    Salary=input.nextDouble();
                    modify(name,Salary);
                    break;

                case 5:
                    if(em!=null) em.close();        //Close EntityManager
                    if(emf!=null) emf.close();        //Close EntityManagerFactory
                    exit=true;
                    break;

                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        }while(!exit);

    }

    static EntityManagerFactory emf=Persistence.createEntityManagerFactory("empDB.odb");
    static EntityManager em=emf.createEntityManager();

    static Scanner input=new Scanner(System.in);
    static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    static int n;
    static String name;
    static Double Salary;
    static boolean exit=false;

    //Query Repository
    static String countQuery="Select count(emp) from Employee emp";
    static String displayAllQuery="Select emp from Employee emp";

}

Now save your project and press the run button or press Ctrl+F11. Now the program should run and you can see output in the Console section present in the bottom pane. This is just a console application. I encourage you to develop a GUI for this!

VI. The ObjectDB explorer tool

Before we finish Id like to introduce you to a very useful tool provided by ObjectDB. Its called the ObjectDB Explorer and it can be used to see what the database files contain. (i.e) you can explore your database without writing code to access it. This can be pretty useful to understand your app and for debugging purposes. You can find the explorer inside the bin directory of Object DB (where you extracted the ObjectDB files). Run explorer.exe. Now you can open a db using the File->Open Local option. Open Remote is done when you are accessing a database stored in a server. Now browse and select the database and open it. Now double click your database shown in the “Persistence Capable Classes” pane in left side. Now the Object Browser will display your DB. You can expand each object in the db to view its contents. Pretty neat huh?

Heres how my database looks like after some insertions…

(again, if you cant see it properly click here…)

This explorer also provides many other options. Feel free to explore ’em!

<END OF TUT. huuhhh!>

I guess you would have got a vivid idea about JPA. I have explained the mere basics of JPA using Object DB implementation. In order to understand more and to increase your knowledge you can refer the ObjectDB manual which provides an elaborate and comprehensive text about JPA with ObjectDB. This is a really useful feature of Java that will help you a lot. Helped me a lot! So try to learn more about it.

As always if you have any doubts or clarifications leave a comment or email me = stevanity[dot]hf[at]gmail.com

Regards,

Steve Robinson.

//PasteBin Source: http://pastebin.com/U18fS409

Simple MultiThreading


I wrote this small program to implement Java’s MultiThreading¬†capabilities. This is the bare minimum that you can do with it. Its extremely powerful and useful and reasonably easy to use. This program is for beginners who cant understand what multi-threading is all about. The program is self-explanatory. As always, for any clarifications or doubts leave a comment below!

import java.util.Scanner;

/**
*A Simple Java program to explain basic MultiThreading.
*@authorSteve Robinson
*@see footyntech.wordpress.com
*/

class ThreadTest implements Runnable
{
    public int buffer=0;
    public void run()
    {
        try
        {
            for(int i=0;i<50;i++)
            {
                buffer+=i;
                Thread.sleep(400);
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("Child Thread Ended");
    }
}

class MultiThreading
{
    public static void main(String arg[])
    {
        ThreadTest temp=new ThreadTest();
        Runnable r=temp;

        Thread thread=new Thread(r);
        thread.start();

        String in;
        Scanner input=new Scanner(System.in);

        System.out.println("Press \"p\" to print current value and \"q\" to quit");
        while(!((in=input.nextLine()).equals("q")))
        {
            if(in.equals("p"))
            {
                    System.out.println("Current Value: " + temp.buffer);
            }
        }
        System.out.println("Stopping Child Thread....\nExiting....");

        //Deprecated method. Please ignore warnings...
        thread.stop();  

    }
}

Complete Source Code:

Pastebin Paste

Steve Robinson

A Simple semi-Scientific Calculator in Java


I made this Calculator Application for a lab experiment in my college. I thought I’d put it out here. But I will not be providing any explanation for the code. The explanation will be covered in a series of tutorials that I will be writing very soon and it deals with the Event Handling techniques and Basic Java Swing programming. So if you have any doubt about the code just drop a comment or email me and Ill be more than glad to help you! And btw, this is for educational purposes only. So dont copy and use it for your School or College home works. And it has a lot of flaws in its design. I just made a quick and simple app. Ill be making a comprehensive one later that will have a lexer and parser in it which enables evaluation of complex expressions. And I forgot to add the keyboard input support. So all that will be coming with Version 2.0! I hope this is useful for you!

Application GUI:

Runnable Jar (V 1.1):

MediaFire Link – Calculator.jar

Source Code (V 1.1):

http://pastebin.com/Q4Muty1a

 

Applet (V1.1)

http://pastebin.com/WDZFRmS8

Im releasing the source code for this. Please report any bugs. And if anyone has advanced this in anyway feel free to post here!

I hope most of you know how to run an applet. Just compile the code using javac and then run the command

appletviewer Calculator.java

Happy Learning,

Steve Robinson

/**

Note: Minor Errors were rectified.

Change Log:

V1.1:

1. Fixed Issues with x^2 and x^3

2. Fixed Issues with “ANS” key

3. Fixed some issues with entering input after an operation

*/