Saturday 28 December 2013

Exhaustive Java Swing Tutorial for Beginners

swing tutorial for beginners
Here is a kickstarter Java Swing tutorial for Beginners that takes you into the ocean of swing slowly and help you reach the other end of the sea without pain and with a very little effort. Well, is it that easy? Yes, it is. Swing is a big topic, I agree but that doesn't mean it's harder, rather you find it more interesting as you move on.

This blog contains of over 100+ articles just on the Swing topic.

Well, this topic is going to be quite big, just take a look at right side (in your browser), You can see the scroll bar is a million miles far away from your bottom-right corner. But wait. Don't worry. If you want to learn Swing, you any ways have to load dozens of pages, I did it one page and great! you already completed loading this page and everything you need is here. This post is interesting, I promise, and by the time it ends, I'm sure you'll thank me!

In a poll, I have conducted on my facebook fan page, I saw 80% of people answering that Swing is their favorite topic in Java. Is it so for you? Discuss in the comments, why you love swing.

“By all means let's be open-minded, but not so open-minded that our brains drop out.” - Richard Dawkins

Now, when we talk of Swing, we need to talk about the basics of GUI which were already discussed in the AWT tutorial. If you aren't familiar with the AWT, I suggest you to learn it or atleast have an idea of it to understand the Swing effortlessly.

Now that you know, what are the advantages of AWT, when there was no thing called GUI, people faced a lot of problems working with commands. Later GUI was introduced and incorporated into many programming languages including our Java. But that was limited and not advanced. It contained only the core components and even violated the Java paradigm as discussed in the awt tutorial. But do you know? AWT is small, isn't it? Yes, it is when compared to that of the Swing. Swing is relatively a larger toolkit with dozens of components you need to explore.

Is Swing easy for an AWT master?

Yeah! it is easy. But you don't really need to be an AWT master. The only thing, the major difference you can learn between the classes in Swing and the AWT are that in Swing you can see an additional J prefix before any component name. For example, in AWT it is Button, in swing it is JButton, TextField is JTextField in Swing. Also swing incorporates AWT Event handling into it.

But isn't there a difference except the prefix? There is!! A big difference is that all Swing components except the top-level containers (JFrame, JDialog) etc are written in pure Java code. While those in the AWT aren't.

“I don't know, I don't care, and it doesn't make any difference!” - Albert Einstein

The problem with AWT components is that they are written in native code (C/C++). So, to create any component they must depend upon the operating system and so the OS look and feel is incorporated into those components. And as the Operating system changes, the visual appearance (a.k.a. look and feel) of the components changes. Is it a problem? Yes, why not?

The javax.swing package

All the swing is tightly packed into a single package called javax.swing. But why is it given a name javax? Well, javax stands for Java's Extended Technology. I call it the Grandson generation of Java because it is advanced. And Oh no!! Are we into an advanced topic? Yes, swing is an advanced topic but you don't need to get frightened of the word because advanced isn't a synonym for harder.

“There are no secrets to success. It is the result of preparation, hard work, and learning from failure.” - Colin Powell

A sub package the javax.swing.event contains event listeners and event classes associated with several swing components. To understand this, you must go through what is event handling. Swing itself uses AWT event handling as said previously for many of its components, so we can conform that Swing doesn't override the AWT.

Disadvantages of AWT

1. Limited set of components. No sliders, progress bars, spinners..
2. Written in native code, looks different on different operating systems.
3. Not highly customizable
4. OS dependent, for each component creation, the JVM has to make calls to the Operating system.
5. AWT components take up more resources, they are slow because they need interaction with the OS.

“Every advantage has its disadvantage” - Proverb

Note: Even the top-level containers in Swing (JFrame, JDialog etc) must depend on the OS because a window (a top-level container) cannot be created without the permission of OS.

Introduction to Swing

Every topic has an introduction so does the Swing. The introduction of swing is a little big, frankly, but not too big to get frightened, I promise. After including this here, I thought it would be better if I write it as another post. So here is the post that teaches Introduction to swing and contains almost everything you need to know.

Model-View-Controller Architecture

Swing supports MVC architecture (Model-View-Controller) based architecture for its components. Here is a kickstart guide on mvc architecture in swing

Swing Components

You need to have a basic understand of the swing components and containment hierarchy before you penetrate into the examples. After going through above post, just continue reading the rest of this post.

Examples on each Swing Component

JFrame

JFrame is a top-level container which is nothing more than a window with a title bar and an optional menu bar.

JPanel

JPanel is a container which is a sub class of JComponent that stores other components in it. This can be added to any top-level container like JFrame and JDialog to group components.


JLabel

JLabel is a light-weight component that describes other components. Users may not know what a component is for, so we use JLabels to tell that information.


JButton

JButton is a nothing more than a push-button which you might already have gone through many times. User can click on it to get anything done.


JToggleButton

A JToggleButton is another component much similar to a JButton. But the difference is a JToggleButton goes into pressed state when mouse is pressed on it. To get that back into normal state, we need to press again. This component is mostly used when there is an on/off situation. You'll get a better idea of what it is when you see it in practical.


JCheckBox

A JCheckBox lies on a single principle, checked/unchecked. This component is mostly used in when we are checking multiple items, for example in Job search site, you might have undergone this where you select multiple skills, a check box is mostly used.


JRadioButton

JRadioButton is also based on the same principle as that of the JCheckBox. But the difference is that a JRadioButton is typically used when the user has to choose only one among the many items in a group. For instance, you can use it for Male/Female, the user has to select either of it, but not both. In AWT, you don't have specified class for JRadioButton as here.

Note: JButton, JToggleButton, JCheckBox and JRadioButton are all sub-classes of AbstractButton.


JComboBox

JComboBox lets the user choose a single item from multiple items. It only displays single item to the user. You can see it in many sites, where they ask you to choose your country.


JList

JList is another light-weight component similar to a JComboBox but with two major differences. The first is that JList shows multiple items (rows) to the user and also it gives an option to let the user select multiple items.


JTextField

JTextField, as you know, is a component used to write a single line of text. A text field can be seen at this blog's side bar, the subscribe field, where you type your email address.


JPasswordField

JPasswordField is much similar to a JTextField but it allows user to type passwords rather than simple text. You know, your text is visible as it is when you type in your email id, but in the case of password, some round black filled circles are displayed which are used to mask your password, but what you type is the same. This class also gives the option to morph the text with the type of character you want, if you don't like that black spot.


JFormattedTextField

This is a different type of JTextField. This allows user to enter a particular type of data. For example, you can restrict the user to enter only date in it, or a number, or a decimal value ranging between 0.0 and 1.0 etc. Anything else that the user types, will not be accepted. You can better understand this, if you look at the example.


JTextArea

JTextArea is allows you to write multiple lines of text. There are a lot of methods in this that you need to explore.


JMenu

A JMenu holds menu items and even other components. You might have already seen this in Notepad, they are named File, Edit etc. When you click them, you see menu items.


JMenuItem

A JMenuItem as said previously, is an item included in a menu where the user can click on it or invoke it by a shortcut. You can see this in Notepad, New, Open, Save etc. are called menu items. You can invoke them either by click on them or selecting them and hitting enter or via a shortcut.


Menu Button [Custom Component]*

This is a custom component. A menu button can be defined as menu that looks like a button (not like a JButton), when you click on it, the menu is displayed. You can see this type of component in My computer toolbar where you will set the view as Thumbnails or icons etc.


JCheckBoxMenuItem

This is a JMenuItem with JCheckBox in it. You might have seen this in Notepad > Format > Wordwrap.


JRadioButtonMenuItem

This is a JMenuItem with a JRadioButton in it. You can better know it and its uses if you take a look at the example.


JProgressBar

A JProgressBar is used to display progress of a process. You might have seen it a thousand times, at least. Most commonly, you have seen it in software install wizards and download managers. They show how much process was done.


JSlider

JSlider is used to let the user slide among values. You have seen it in Youtube, while playing a video, you can seek the video where ever you want, the one that you click on to do this is an example of slider.


Volume Component [Custom]*

A volume component is a slider with a JMenu. As said previously, you can also add custom components to JMenu apart from JMenuItems. Here a JSlider is added.


JSpinner

A JSpinner is used to spin between values. You might have seen it in setting RGB values of a color in many software. It contains a text field like editor in which you can type a value or it contains two small up and down buttons which allows you to change the values in the editor.


JTable

Who doesn't know what is a table? With the help of this class you can create JTable with column headers, insert custom type of data, components and what not, everything you can insert in a table. But for some things we need to hack.


JTree

A JTree is like a tree that contains several branches, even some branches contain sub branches. More about it clearly, with a diagram is explained in this example, I'm sure you'll understand it.


JToolBar

A JToolBar is used to create tool bars. A tool bar contains multiple components in it. You might have seen a toolbar many times, one such place is your book marks bar in your browser, which is a toolbar.


JTabbedPane

JTabbedPane is used to create tabs. Tabs lessen the space in a container by displaying only one group of data at a time. The best example, is your browser tabs where you open a new tab every time you want to open a new page.


JDialog

JDialog is a top-level container that doesn't contain minimize and maximize buttons, but still it is resizable. A JDialog typically takes a JFrame as a parent.


JFileChooser

A JFileChooser is used to let the user browse for files. You have seen it in Notepad, when you click on Open or Save. That specific dialog is called as a file chooser.


JColorChooser

A JColorChooser is a dialog that comes with several components that help user to choose from a large variety of colors.


Friday 6 December 2013

Connect to MongoDB As a Service via Java Program

In this example, I am going to show you how to connect to MongoDB as a service via our Java program in 5 simple steps.

First of all, let us know what is MongoDB as a service. This means that our MongoDB is offered as a service online from the creators of MongoDB i.e. the database will be online in their computer (server) and that we will store our data there without the need of installing database (MongoDB here) in our system (where our program exists). Clear? OK. Let us now move on to the program.

Signing Up for MongoDB as a service

  1. For this, first we need to Sign Up to the database-as-a-service (DaaS) from MongoLab. In the free account you get 500 MB for free which is enough for our practice.
  2. After signing up, you will receive a confirmation email. After confirming, you can click on the Login button to login to the website.
  3. Now you need to create a database. For this click on the Create Database link in the URL.
  4. Select the Development (single node) tab and select the FREE version. You will see some cloud providers like amazon, rackspace, windows azure etc to choose your platform. You don't need to worry about them much now. It is where your database exists, nothing more that.
  5. Now, give a database name which you will be using in the program.
  6. Now click on Create new MongoDB deployment button to complete the process.
  7. Now click on the database you have created and click on Add collection. A dialog appears, give the collection a name and click on Create.
  8. Now, you can see an yellow box which says that
  9. A database user is required to connect to the database. Click here to create a new one.
  10. Click on that, give a user name, password and password confirmation. That's it. This is your database user name and password which you will use in your program. Don't check the option read-only, if you do that user will be unable to insert data into that database.
In a rounded box above, you could see something like this:
mongodb://<dbuser>:<dbpassword>@ds023288.mongolab.com:23288/sample

This is called as the database URL with which you can connect to the database in the Mongo DB. In the above url, you need to replace <dbuser> and <dbpassword> with the database Username and password that you have given in the dialog.
Here my database name is sample (see what you have kept) and my collection name is mycollection

Connecting to MongoDB via program

Now, you know five things:
1. Your database name, collection name, database username, password and the database URL.

Before we continue, we need to download the API for Java. Download this mongo 2.10.1.jar and include it in your class path. Now let us go into the program.


import com.mongodb.*;
class MongoConnect
{
    public static void main(String args[]) throws Exception
    {
        // The text uri
        // "mongodb://xyz:MyPass_XYZ@ds023288.mongolab.com:23288/sample";
        // Give the url of your database by replacing
        // xyz with your username and MyPass_XYZ with your password
        String textUri = "mongodb://xyz:MyPass_XYZ@ds023288.mongolab.com:23288/sample";

        // Create MongoClientURI object from which you get MongoClient obj
        MongoClientURI uri = new MongoClientURI(textUri);

        // Connect to that uri
        MongoClient m = new MongoClient(uri);

        // get the database named sample
        DB d=m.getDB("sample");

        // get the collection mycollection in sample
        DBCollection collection = d.getCollection("mycollection");

        // Now create a simple BasicDBObject
        BasicDBObject b=new BasicDBObject();
        b.put("name","Gowtham Gutha");
        b.put("site","java-demos.blogspot.com");

        // Insert that object into the collection
        collection.insert(b);

    }
}

The BasicDBObject can take multiple key-value pairs which will be inserted into the collection. The insert method inserts all the key-value pairs associated with that collection object. To confirm whether the values are inserted you can go to the page (or refresh it) and you can see them.


https://mongolab.com/databases/your_database_name/collections/your_collection_name

Replace, your_database_name with the name of your database (here it is sample) and your_collection_name with the name of collection (here it is mycollection) and every thing is same. You must be logged in to see these. Remember.

So, in this way, we can simply connect and use MongoDB as a service from our Java program.

Monday 2 December 2013

7 Ways of loading a JDBC Driver You Might Not Know

When I say there are 7 ways of loading a JDBC driver, YES, I am right and you are here for it. Let me show you 7 simple programs, 1 way in each.

I split these examples into two specific categories which are good and dumb. Well, does this blog post dumb things? No, but still, this post is to show that there are such ways. Let me show them so that you could better grasp what fits the best.

class dr1
{
    public static void main(String args[]) throws Exception
    {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    }
}


class dr2
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime
        Class.forName(args[0]);
    }
}


class dr3
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime by a temporary
        // property
        Class.forName(System.getProperty("my.driver"));
    }
}

For executing this, you should write

java -Dmy.driver=oracle.jdbc.driver.OracleDriver dr3

The -D option is followed by the property name (without space) and = followed by the driver class. Don't forget the class name. It is damn important!

Note: The second, third and fourth ways have a common problem. Here if we aren't decisive about which driver to use and give it at runtime we need to change the URL (to connect to the database) too. Because, different drivers have different urls. So, there must be some conditional logic written which connects to the database via appropriate URL corresponding to the given class name. This becomes a bit messy. Isn't it?


class dr4
{
    public static void main(String args[])
    {
        // Choosing the driver at runtime by a permanent
        // property
        System.out.println("Driver loaded "+System.getProperty("jdbc.drivers"));
    }
}

Well, where is the code? I'll explain, everything lies in executing the program. You should execute this in this way.

java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver dr4

Now, this loads the driver. The jdbc.drivers is an environment property of Java that corresponds to the JDBC drivers. The default value for this property is null. While executing, you are changing its value to the driver class name.

3 Dumb ways


class dr5
{
    public static void main(String args[])
    {
        // Creating an object for the driver class
        new oracle.jdbc.driver.OracleDriver();
    }
}

I call this dumb because, we are creating an object for this class which is absolutely unnecessary. Here is a simple question to you

Why create an object for a class when you are not going to use it? If you want to load the static block of the class? Isn't it enough to load the class into the memory using Class.forName() instead of creating an object for it?


class dr6
{
    public static void main(String args[]) throws Exception
    {
        // Using the registerDriver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    }
}

This way is double-dumb because you are loading the driver twice. Yes, the static block of the oracle.jdbc.driver.OracleDriver already contains a call to the registerDriver(). The statement, new oracle.jdbc.driver.OracleDriver(); loads it into memory (therefore, static block is executed) and creates an object for the driver class and then register the driver.


class dr7 extends oracle.jdbc.driver.OracleDriver
{
    public static void main(String args[])
    {
        System.out.println("Driver is loaded.");
    }
}

This is triple-dumb because Java doesn't support multiple inheritance. What if we want to extend this class with some other class?
This method however, does the job. The static block of the super class (the driver class here) gets executed and the regsiterDriver() is called. Here is a question to you.

Why extend a class when you can simply create an object for it? Also, don't forget to answer the previously posed one, which is the tail of this question.

Photo Credit: S3V3R!7Y

Sunday 1 December 2013

What is Class.forName() and Why should we use it?

Class.forName() is a static method of the java.lang.Class that loads a given class into the memory. Didn't understand what is loading of a class into memory? Well let me explain.

Loading of a class into memory is nothing but loading it into RAM, thereby making it accessible to create an object for it and work with it.
When a class is loaded, its static block is executed.

Here is an example on Class.forName()

class ForNameEx
{
    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("oracle.jdbc.OracleDriver");
        System.out.println("Driver loaded");
    }
}

The above example loads a class called oracle.jdbc.OracleDriver (a class related to JDBC). If you don't have an idea about JDBC, just leave the class name. I just showed it as an example. This method, Class.forName() throws a ClassNotFoundException which clearly means that, it is an exception thrown when the class sent to the Class.forName() is not found. If this happens, then the next statement here isn't executed.

Now, as said earlier, when a class is loaded into the RAM, its static block is executed. Here, the static block in the oracle.jdbc.OracleDriver class is executed. So when we want to execute the static block of a class without creating an object for it, this is a way.

Returns: This method returns the Class object of the given class name.