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.

Wednesday 27 November 2013

One Point about For Each Loop I Ridiculously Forgot

Laughing at me! ;)
Laughing at me! ;)
It is very shameful that I forgot this simple point and had written a post on for-each loop previously.The point is that for-each loop can be used to iterate through an iterator. See this snippet..

ArrayList<String> as=new ArrayList<String>();

as.add("Item 1");

as.add("Item 2");

as.add("Item 3");

as.add("Item 4");

for(String st:as){

System.out.println(st);

}

It is not just for an ArrayList but for any iterator.
In fact, for each loop is designed for this. But I forgot that. I apologize for the readers that I had missed that most-important point in that post. I thought of updating it, but I need to show off my mistake, so did I write this post. Also take a look at what oracle has written about for-each loop.

Photo credit: Wikimedia

Autocomplete HTML Input Field using JSP and JQuery in Five Lines!


Everyone is fascinated about auto-complete. Right? I think, Are you? Drop in the comment below. Long time I've been connecting JQuery and Java and have some of the posts like loading JSP file in JQuery in one line Now, it is time to go further.

I would be blogging now a simple example on how to connect auto-complete for a HTML text field to a JSP file with JQuery in one line! Yes, in five lines!, YOU heard it RIGHT!

Project structure

Folder path: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_autocomplete



jq_autocomplete

                |

                +-- index.html

                +-- auto.jsp

index.html - HTML file



<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
                // When any key is down
                $(document).keydown(function(){

                    // Get the input element and its value
                    var i=$("#com");
                    var val=i.val();

                    // Send request only if user types alphabet
                    // because auto.jsp returns names of companies
                    // which contains only alphabets
                    if(val.match(/^[A-z]+$/))
                    {
                        // Send request and get the data
                        $.get("auto.jsp?com="+val,function(data){

                            // Get each item separated by new line
                            var items=data.split("\n");

                            // put those items in autocomplete! That's it!
                            i.autocomplete({source:items});
                        });
                    }
                   
                });
        </script>
    </head>
   
    <body>
        <input type="text" id="com" name="com"/>
    </body>
</html>

The point here is that the function keydown is executed every time when a key is down in the document and so the request will be sent each time when the key is down degrading performance of the application. To avoid this, the if-condition is useful which checks if the value matches the regex which corresponds to any alphabet.

auto.jsp - Returns auto complete data



<%@page import="java.util.*"%>
<%
    // Create ArrayList and add some items
    ArrayList<String> as=new ArrayList<String>();
    as.add("Google");
    as.add("Yahoo");
    as.add("Apple");
    as.add("Microsoft");
    as.add("Linkedin");
    as.add("Facebook");
    as.add("IBM");
    as.add("Oracle");
    as.add("Salesforce");
    as.add("Amazon");
   
        String s=request.getParameter("com");
       
            for(String st:as)
            {
                if(st.toLowerCase().startsWith(s.toLowerCase()))
                {
                    out.println(st);
                }
            }
%>

The best price you could pay for this post is sharing it. I thank you in advance :)
Photo Credit: Angelina :) via Compfight cc

Monday 25 November 2013

Send POST Request to Servlet in JQuery in One Statement!

Post request with JQuery
Here is a single-line statement to send a POST request to a servlet with JQuery. This is gonna be dead simple. Yes, so simple that it is nothing more than a JQuery method call. Curious about what the method is? Me too! It is none other than..

post(): There are a lot of versions of this method. But here, we are going to use the simple version which takes the url-pattern and the data to be submitted.

Project structure

Folder: D:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_post


jq_post
        |
        +-- index.html
        +-- WEB-INF
                    +-- classes
                            +-- simple.java
                            +-- simple.class

index.html


<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
        <script>
            $(function(){
           
            $( "#hform" ).submit(function(event) {
           
                // Stop form from submitting normally
                event.preventDefault();
               
                // Get some values from elements on the page:
                var form = $(this);
               
                // Get the value in input uname
                term=$("input[name='uname']").val();
               
                // Send the data using post
                var posting = $.post("hello",{uname:term});
               
                    // When the POST request is done..
                    // data: The output printed in servlet
                    posting.done(function(data) {
                       
                        // Put the results in a div
                        $("#view").append(data+"<br/>");
                       
                    });
            });
            });
        </script>
    </head>
   
    <body>
   
        <!--Create the form-->
        <form id="hform" action="/jq_post/hello" method="post">
            <input type="text" name="uname"/>
            <input type="submit" value="SUBMIT"/>
        </form>
        <!--Create the form-->
       
        <div id="view"/>
    </body>
   
</html>

web.xml - Deployment descriptor



<web-app>
    <servlet>
        <servlet-name>ser</servlet-name>
        <servlet-class>simple</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>ser</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Related: What is web.xml in servlets?

simple.java contains doPost()



import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class simple extends HttpServlet
{
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
        // Get the user name from html input field
        String name=req.getParameter("uname");
       
        // Get PrintWriter obj using getWriter() in HttpServletResponse
        PrintWriter pw=res.getWriter();
       
        // Print, that's it!!
        pw.println("Hello "+name+"!");
    }
}

Image credit: tuicool.com

Saturday 23 November 2013

Compile and Run Java Programs in One Click!

Here is how we can compile and run Java programs in one click. Yes, you heard it right and that is absolutely true. What about commands? Do i need to write them. Of course, you need them, but you don't need them to type always.

Creating a batch file lets you do this. In this post you'll learn how to compile all Java programs, wait till the output is seen, hide the echo as well!

Before we start, let us talk a bit about the batch files.
  1. They are the files which contains a set of commands that are executed in the command prompt one by one.
  2. They are saved with a .bat extension.
  3. Whenever you click on that file, those commands are executed one after the other.
So, it is clear that you need to write the two commands that compile and execute your program. They are javac MyProgram.java and
java MyProgram
OK. That's it? Can we just include these two lines and save the batch file? Hmm, but you can't see the output, unless it is a GUI program. Because, the output is printed and the command prompt is closed. That's it. Now, is there a solution? Yes, here it is.

Pause batch file to display output


@echo off
javac MyProgram.java
java MyProgram
pause

The pause command stops the command prompt from exiting.
The @echo off command doesn't display the path of the directory in the command prompt. For instance, if you are executing this in the folder E:\java then E:\java> is not visible. Just see it in practice for a clear understand.

Though there are any errors, then the second command is executed. The program will run depending upon the previous class file (if any). Otherwise, could not find or load main class MyProgram error will be displayed.
To prevent this, you can delete the previous class file and that command should be placed before.

Stop executing previous class file code [Use with caution]


@echo off

del MyProgram.class

javac MyProgram.java

java MyProgram

pause

I recommend you to use this with caution, once the previous class file is deleted, you might not get back your code. Your program stays fine, but it is a modified version that contains errors.

One last tip, to compile all the classes, use javac *.java

@echo off

javac *.java

pause
However, you cannot execute all programs at a time. You'll need to write one by one.

Writing and saving them?

Simple,
  1. Write those commands in notepad and save them in the directory where your Java programs are present.
  2. Click on that batch file, every time you write it!
  3. To make your life more easy, just create a shortcut for that batch file on your desktop
and here we go, click it every time to compile and run!

If you like this post, please share it, it would be the highest price you could pay for this post.

Image credit: logopond.com

Load a JSP File using JQuery in One Line


Here is how to load a JSP file using JQuery in a single line!. The following is a hello world JSP example which will be loaded on a button click using the JQuery. As you can see from the image, the paradigm, write less, do more. is exactly exemplified here.

Project structure

Folder: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_jsp

jq_jsp

    |

    +-- index.html

    +-- hello.jsp


index.html




<html>


<head>


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the document is ready..


$(document).ready(function(){


// When any element with input tag is clicked


// execute the following function


$("input").click(function(){


// Get object of element with loadHere id


// And in it load the hello.jsp file!


$("#loadHere").load("hello.jsp");


});


});


</script>


<title>Load a JSP File in JQuery</title>


</head>




<body>


<input type="button" value="Get hello"/>


<div id="loadHere"/>


</body>


</html>


hello.jsp




<%


response.getWriter().println("Hello world!");


%>


The greatest appreciation you could give me is sharing this article. I would sincerely appreciate it :)

Friday 22 November 2013

Submit a Form to Servlet using JQuery

Here is how to submit a form in background to servlet using JQuery in one single line. The scope of the program is to print a hello message in a html div. Note that you need to have a basic knowledge of JQuery and Javascript to understand this. But I'm pretty sure that the helpful commentaries will give you an understanding even if it is your first sight :)

Folder structure

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\jqform

Project structure



jqform


|


+-- index.html


+-- WEB-INF


+-- web.xml


+-- classes


+-- simple.java


+-- simple.class


HTML Files

index.html




<html>


<head>


<title>JQuery - Servlet form submission</title>


<!--To use jquery, loading this is mandatory-->


<!--If you don't have internet connection, download this file


and give the local path


-->


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the page is loaded, then..


// execute this function


$(document).ready(function(){




// When the button with id submit


// is clicked, this function should


// be executed


$("#submit").click(function(){


// Get the value in the val field


var val=document.getElementById("t").value;




// Now, get the element with id displayMsg


// and in it load the given file


// The text printed in the servlet class now


// comes in the displayMsg div


$("#displayMsg").load("/jqform/go?q="+val);


});


});


</script>


</head>




<body>


<input type="text" name="q" id="t"/>


<input type="button" id="submit" value="SUBMIT"/>


<div id="displayMsg"/>


</body>




</html>


Here, the load() method takes a string which corresponds to the page that is to be loaded. Here, we are indirectly calling the page http://localhost:8080/jqform/go?q=gowtham (when you type 'gowtham' in the input field) and that the content in the page is pasted in the displayMsg division. In other words, simply, the above page is loaded in the div instead of a new page. That's it.

Deployment Descriptor

web.xml




<web-app>


<servlet>


<servlet-name>puppy</servlet-name>


<servlet-class>simple</servlet-class>


</servlet>




<servlet-mapping>


<servlet-name>puppy</servlet-name>


<url-pattern>/go</url-pattern>


</servlet-mapping>




</web-app>


Servlet Programs

simple.java




import javax.servlet.*;


import javax.servlet.http.*;


import java.io.*;


public class simple extends HttpServlet


{


public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException


{


String q=req.getParameter("q");




// Get write object and print


PrintWriter pw=res.getWriter();


pw.println("Hello "+q);


}


}


Thursday 21 November 2013

Set Notepad Icon for JFrame in Swing

Here is how to set notepad icon for JFrame in Swing. Yes, you heard it right. But is it simple. Dead simple. Just see it below.

import javax.swing.*;

import java.awt.*;

import java.io.*;

import javax.swing.filechooser.*;

class WindowsIconForJFrame extends JFrame

{

public WindowsIconForJFrame()

{

createAndShowGUI();

}



private void createAndShowGUI()

{

setTitle("Windows Icon");

setDefaultCloseOperation(EXIT_ON_CLOSE);



ImageIcon i=(ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(new File(System.getenv("windir")+"\\notepad.exe"));

setIconImage(i.getImage());



setSize(400,400);

setVisible(true);

setLocationRelativeTo(null);

}



public static void main(String args[])

{

new WindowsIconForJFrame();

}

}

FileSystemView.getFileSystemView(): This method gets the FileSystemView object which contains the getSystemIcon() method which takes java.io.File as parameter. The file object is corresponded to the notepad.exe. To work with this program, make sure that you have notepad in your system.

setIconImage(i.getImage()): This method takes java.awt.Image which can be obtained using getImage() in javax.swing.ImageIcon class.

Notepad icon for JFrame

Related: How to set default system icons for JFileChooser?

Wednesday 20 November 2013

Background Form Submission in Servlets

Here is how to submit a HTML form in background without leaving the page. This is a simple example that doesn't make use of the AJAX. I could rather say it as a simple HTML technique.

This is in fact a long lasting dream of mine. While I am satisfied, I ain't completely satisfied. However, this WILL help you if you don't want to submit the form normally or in background with AJAX.

In this example, I've put a simple <iframe> which isn't displayed. When the user clicks on the button, the thing is done in background. But the problem here, is that we don't know the response from the server. We just need to hope that the things are done fine.

I would STRONGLY recommend using AJAX if you would like to know the response from the server. This is the best way. The entire page here is being loaded, but the only thing is that it isn't visible to the user thereby giving him a feel that the form is submitted in the background.

Folder structure




webapps


|


+- bs


|


+- index.html


+- WEB-INF


|


+- web.xml


+- classes


|


+- servlet.java


+- servlet.class


HTML File




<html>


<head>


<title>Background Form Submit</title>


</head>


<body>


<form action="/bs/submit" method="post" target="m">


<input type="text" name="q" size="40"/>


<input type="submit" value="SUBMIT"/>


</form>


<iframe name="m" style="display:none"/>


</body>


</html>


Here as the target of the submit page is iframe which is not displayed, there is nothing the user can see that a new page is loaded.

web.xml - Deployment descriptor




<web-app>


<servlet>


<servlet-name>myser</servlet-name>


<servlet-class>servlet</servlet-class>


</servlet>




<servlet-mapping>


<servlet-name>myser</servlet-name>


<url-pattern>/submit</url-pattern>


</servlet-mapping>


</web-app>



servlet.java - Program to write to a file


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class servlet extends HttpServlet

{

public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException

{

String q=req.getParameter("q");



// I am writing it to a file

FileOutputStream fout=new FileOutputStream("out.txt");

fout.write(q.getBytes());

fout.close();

}

}

Note: The file out.txt is written in the Tomcat folder (ex. Tomcat7.0) but not in the project directory. In the next example i'll be telling how to submit form in background using AJAX, so that you get the response from the server too.

Monday 18 November 2013

Get Global Mouse Pointer Location in Java in One Statement

global mouse location
Here is how to get global mouse pointer location in Java using a single statement. Yes, you heard it right, in a single statement!!

import java.awt.*;
class GetPointerLoc
{
    public static void main(String args[])
    {
    // Get global current cursor location
    Point p=MouseInfo.getPointerInfo().getLocation();
   
    System.out.println(p);
    }
}

getLocation(): This method is present in the java.awt.PointerInfo class. The object for this class can be created using the getPointerInfo() method in the java.awt.MouseInfo class.
Image credit: Iconarchive

Move Mouse Pointer with Arrow Keys in Java

moving mouseYes, you are able to move mouse pointer with arrow keys in Java globally and that is theme of the below program. With the help of this program, the cursor pointer goes up when UP arrow key is pressed, down when down arrow key is pressed.... and press the mouse when enter is pressed. Isn't that cool? Let us take a look at the example below.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MoveCursor extends JFrame
{
Robot r;

    public MoveCursor()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Move Cursor with Keyboard");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // hide the visibility
        setUndecorated(true);
        setOpacity(0f);
        setVisible(true);
       
        // Create Robot object
        try
        {
        r=new Robot();
        }catch(Exception e){}
       
        addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e)
            {
                // If there occured an exception
                // while creating Robot object, r is null
                // then go back
                if(r==null) return;
               
                // Get global current cursor location
                Point p=MouseInfo.getPointerInfo().getLocation();
               
                switch(e.getKeyCode())
                {
                    case KeyEvent.VK_UP: r.mouseMove(p.x,p.y-1); break;
                    case KeyEvent.VK_DOWN: r.mouseMove(p.x,p.y+1); break;
                    case KeyEvent.VK_LEFT: r.mouseMove(p.x-1,p.y); break;
                    case KeyEvent.VK_RIGHT: r.mouseMove(p.x+1,p.y); break;
                    // left click
                    case KeyEvent.VK_ENTER: r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseRelease(MouseEvent.BUTTON1_MASK);
                }
            }
        });
    }
   
    public static void main(String args[])
    {
        new MoveCursor();
    }
}
MouseInfo.getPointerInfo().getLocation(): This method is present in the PointerInfo class whose object can be obtained by getPointerInfo() method in the MouseInfo class. getLocation() returns the current mouse pointer location which is helpful in moving the cursor with arrow keys.

3 JProgressBar and JSlider Examples for a Kickstart

Here are three examples on JProgressBar and JSlider examples that will kickstart your journey. In this tutorial, you will learn:
  1. What is a JProgressBar?
  2. What is a JSlider?
  3. Working with JProgressBar (for beginners)
  4. Coding JProgressBar and Thread class together
  5. Creating JProgressBar using Timer in Swing (Requires to learn event handling)
  6. Working with JSlider (for beginners)

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.
  1. JProgressBar in Swing Example for Beginners
  2. Coding JProgressBar and Thread together

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.
  1. 4 Ways to create a JSlider in Swing

Ace JTextField, JPasswordField and JFormattedTextField Completely

Here are three complete tutorials on JTextField, JFormattedTextField and JPasswordField that you need to ace to be a better swing programmer.

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.

18 Rock Solid Reasons Why You Should Use an IDE

I've been working with an IDE since a couple of years for building my applications. None of my applications were built using Notepad or a similar text editor. There are a quite reasonable amount of reasons which I would like to share why you should use an IDE.

First of all an IDE is an Integrated Development Environment, where you not only write code, but also compile, execute them. It is the only thing you need to complete building an application at the core level, regardless of the testing. The two great IDEs I personally use and of course, most programmers do are NetBeans and Eclipse.

Which one do you use and why?

I use NetBeans to develop desktop applications. I find it easy to create efficient GUI applications in NetBeans because of its simple drag and drop GUI editor which makes my life easy. It doesn't however mean that NetBeans isn't great for building web applications, I haven't built them till date and I don't know how it tastes in it.

I use Eclipse (I changed to Kepler from Indigo recently) to develop web applications. Eclipse is the most popular IDE especially for Java, and there is no doubt in that. Its wide range of plugins often push it to the top of the table.

I first encountered eclipse when researching about Google AppEngine. The tutorials on how to deploy an app to AppEngine frightened me because I have no idea about GIT, pushes and pulls. I thought it would be better if I could do it simply, so did I encounter the Google AppEngine plugin for eclipse.

That's it, with that I've deployed my tiny-apps iGo4iT Search, Google Time and OldSATQ using this eclipse plugin.

Both of the IDEs no doubt are a typical programmer's favorites. But what differentiates them is the environment and the project needs. For programming job seekers, most companies do require to learn at least one IDE.

After a long chat about Eclipse and NetBeans, we need to move forward into the reasons why you are here the ROCK SOLID reasons that you're eagerly waiting for..
  1. Detect compile time errors while writing like semicolon, braces, variable and method declarations etc.
  2. Knowing unknown methods, classes and interfaces. You just need to type a package name followed by a dot (.) and then see the auto complete magic which lists all the sub-packages and classes in it.
  3. Colorful code makes it easy to debug. Who doesn't like colors? When symbols are of one color, keywords are another color, then we can easily detect where a brace is opened, and where it should be closed etc.
  4. IDE notifies if a specific part of code can degrade performance.
  5. Coding convention, smarter way to code: IDE automatically suggests shorter versions of statements we've written.For example, if you write multiple catch blocks, it suggests to replace it with multi-catch specification.
  6. Using external libraries is simple: They're just done in a single click. You don't need to modify classpath settings in your OS. Just clicking on Add Jar and pointing to the library, does it all.
  7. Search for source code: You can search those libraries in the project and see their source code just by typing the classname and hitting enter. In NetBeans, you have it in the top-right corner.
  8. Performance tests can be done in the IDE.
  9. Navigate to errors easily: When there occurs an error or exception in the program, you can navigate to that statement by clicking on the corresponding link in the compile log.
  10. Build GUIs with ease: GUI builders in IDEs need not require the programmer to have knowledge about layouts, the front-end desigining is done by simple drag and drop as said earlier.
  11. Basic code is automatically written: The IDE writes some basic code for you automatically, for example when you put a button on the GUI builder and selected to add an ActionListener for it, then IDE writes an empty handler (actionPerformed) instantly.
  12. Diffing Files allows you to see differences that you've made to the program, its previous versions and other programs as well. This ignites an idea of what went wrong.
  13. Fix imports: Import statements are automatically fixed with a single shortcut (Ctrl+Shift+I in NetBeans) by adding essential ones and removing the unnecessary.
  14. Tab based browsing allows you to move from one program to other easily.
  15. JavaDoc in auto-complete will give you an idea of what you are going to use in the program.
  16. Plugins to deploy applications: You can deploy applications like publishing them to the cloud or wrapping into an exe file etc with simple plugins.
  17. Compiling and executing without command prompt, with simple shortcuts.
  18. Database connections and configurations can be done in the IDE itself without the need of modifying paths in the Environment variables in OS.
Starter programmers need not find any use in the IDEs, but for application development you must learn them and there is no way, you SHOULD use them.

    Store the Largest Number You Can in Java

    Yes, you can store the largest number YOU can think of. So, what is the largest number that came into your mind, right now? Think of adding it, subtracting it, multiplying or at least dividing it with something? I am so curious about this. Aren't you?

    So, let's have some questions, what is the maximum number a long type variable can store? It is 263 - 1, signed. In Java SE 8, for unsigned long it is 264 - 1. Now I do need big numbers than that? Why suspense? You might already have looked into the program, by the time you are reading this? Am I right?

    But wait, let us know at least a bit about the java.math.BigInteger class. One of its constructors takes a String as parameter which I'll use in the program for now. That string can contain the largest number you want, it is on which operations are done. Just as in the String class, operations on BigInteger cannot take place on itself, instead a new BigInteger object is created as a result.


    import java.math.*;
    class BigInt
    {
        public static void main(String args[])
        {
            BigInteger b=new BigInteger("99983938302383039");
          
            // print the value
            System.out.println("The value is "+b);
          
            // To add value
            // A new value is returned but the original
            // isn't modified, just as in String
            System.out.println("Sum "+b.add(new BigInteger("90908977686")));
          
            // To subtract
            // calling big integer - parameter big int
            System.out.println("Difference "+b.subtract(new BigInteger("1000000")));
          
            // To multiply
            // calling * parameter
            System.out.println("Product "+b.multiply(new BigInteger("1000000")));
          
            // To divide
            // calling / parameter
            System.out.println("Division "+b.divide(new BigInteger("10000000000000000")));
          
            // To power, for this time only int, now with BigInteger :(
            System.out.println("Power "+b.pow(10));
        }
    }

    There are still a lot of methods in the BigInteger class that you need to explore. Check out other articles in this blog, there are over 300+, there will at least be 50 which WILL help you in the future.

    Please share this post, if you got what you are here for.