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.

    Sunday 17 November 2013

    AbstractButton and its sub classes - Tutorial

    Here is a complete list of exhaustive tutorials on JButton, JToggleButton, JCheckBox, JRadioButton which will help you ace all the children of AbstractButton.
    Let us now look about what they are.

    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.

    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.

    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.

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

    ObjectInputStream — Reading Object From a File

    This example will show you how to read a Java object from a file using ObjectInputStream. This is a part of serialization topic.

    import java.io.*;

    class ReadObj

    {

        public static void main(String args[]) throws Exception

        {

            FileInputStream fin=new FileInputStream("obj.dat");

           

            ObjectInputStream oin=new ObjectInputStream(fin);

           

            String st=(String)oin.readObject();

           

            System.out.println(st);

        }

    }


    Here, the file obj.dat contains a String object in it. You need to note that to read an object from a file, you need to write it to that file first. The previous program will show you how to write an object to a file.

    fin=new FileInputStream("obj.dat"): This statement creates a FileInputStream object pointing to obj.dat
    oin=new ObjectInputStream(fin): This statement creates an ObjectInputStream object pointing to FileInputStream object fin.
    oin.readObject(): This method in ObjectInputStream class reads an object from the file obj.dat and returns it. As this method returns java.lang.Object, type casting is necessary.

    ObjectOutputStream — Writing Object To a File

    This example illustrates using ObjectOutputStream to write an object to a file. This is a part of serialization tutorial.

    import java.io.*;

    class WriteObj

    {

        public static void main(String args[]) throws Exception

        {

            FileOutputStream fout=new FileOutputStream("obj.dat");

           

            ObjectOutputStream out=new ObjectOutputStream(fout);

           

            String st="I am written in the file.";

           

            out.writeObject(st);

           

            out.close();

            fout.close();

        }

    }


    fout=new FileOutputStream("obj.dat"): This statement creates a FileOutputStream object pointing to obj.dat
    out=new ObjectOutputStream(fout): This statement creates an ObjectOutputStream object pointing to the given FileOutputStream object.
    writeObject(st): This method in the ObjectOutputStream class writes a String object to the file obj.dat

    Saturday 16 November 2013

    java.io.SequenceInputStream — Everything You Need to Know

    Here are two SequenceInputStream examples that you should know. First of all, a SequenceInputStream is an input stream object pointing to multiple input streams. It can read data from several InputStreams in the given order. You can combine files using this class.

    In this tutorial, you'll know
    1. Constructors and Methods of java.io.SequenceInputStream class
    2. Printing data read from SequenceInputStream
    3. Writing SequenceInputStream to a file using FileOutputStream
    The first example is on the first constructor which takes two InputStream objects and the second is on the last constructor which takes an enumeration of InputStream classes. Let us have a look.

    public SequenceInputStream(InputStream s1,InputStream s2)

    public SequenceInputStream(Enumeration<? extends InputStream> e)


    Here are the methods of SequenceInputStream

    // Returns the no.of bytes pointing to the SequenceInputStream

    public int available()


    // Close the SequenceInputStream

    public void close()


    // Read each byte from the SequenceInputStream and return it

    public int read()


    // Read upto len bytes from offset into a byte array b

    public void read(byte[] b,int off,int len)


    Example on SequenceInputStream using first Constructor



    import java.io.*;

    class SequenceInputStreamFirstCon

    {

        public static void main(String args[]) throws Exception

        {

        SequenceInputStream sin=new SequenceInputStream(new FileInputStream(args[0]),new FileInputStream(args[1]));

       

        int k;

       

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

       

            while((k=sin.read())!=-1)

            {

                fout.write(k);

                System.out.print((char)k);

            }

       

        sin.close();

        fout.close();

        }

    }



    Example of SequenceInputStream class using second constructor



    import java.io.*;

    import java.util.*;

    class SequenceInputStreamExample

    {

        public static void main(String args[]) throws Exception

        {

        Vector<FileInputStream> v=new Vector<FileInputStream>();



            for(String k:args)

            v.add(new FileInputStream(k));

       

        SequenceInputStream sin=new SequenceInputStream(v.elements());

       

        int k;

       

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

       

            while((k=sin.read())!=-1)

            {

                fout.write(k);

                System.out.print((char)k);

            }

       

        sin.close();

        fout.close();

        }

    }


    Friday 15 November 2013

    Create an Advanced Chat Box in Java

    The following example illustrates creating an advanced chat box in Java in Swing that detects whether the user is thinking or typing and displays the message accordingly. This chat box is just for demo purpose and it doesn't use any of the networking concepts to interact with the second person.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class Chatbox extends JFrame
    {
    JPanel jp;
    JTextField jt;
    JTextArea ta;
    JLabel l;
    boolean typing;
    Timer t;

        public Chatbox()
        {
            createAndShowGUI();
        }
       
        private void createAndShowGUI()
        {
       
            // Set frame properties
            setTitle("Chatbox");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
           
            // Create a JPanel and set layout
            jp=new JPanel();
            jp.setLayout(new GridLayout(2,1));
            l=new JLabel();
            jp.add(l);
           
            // Create a timer that executes every 1 millisecond
            t=new Timer(1,new ActionListener(){
                public void actionPerformed(ActionEvent ae)
                {
                    // If the user isn't typing, he is thinking
                    if(!typing)
                    l.setText("Thinking..");
                }
            });
           
            // Set initial delay of 2000 ms
            // That means, actionPerformed() is executed 2500ms
            // after the start() is called
            t.setInitialDelay(2000);
           
            // Create JTextField, add it.
            jt=new JTextField();
            jp.add(jt);
           
           
            // Add panel to the south,
            add(jp,BorderLayout.SOUTH);
           
           
            // Add a KeyListener
            jt.addKeyListener(new KeyAdapter(){
                public void keyPressed(KeyEvent ke)
                {
               
                    // Key pressed means, the user is typing
                    l.setText("You are typing..");
                   
                    // When key is pressed, stop the timer
                    // so that the user is not thinking, he is typing
                    t.stop();
                   
                    // He is typing, the key is pressed
                    typing=true;
                   
                    // If he presses enter, add text to chat textarea
                    if(ke.getKeyCode()==KeyEvent.VK_ENTER) showLabel(jt.getText());
                }
               
                public void keyReleased(KeyEvent ke)
                {
               
                    // When the user isn't typing..
                    typing=false;
                   
                    // If the timer is not running, i.e.
                    // when the user is not thinking..
                    if(!t.isRunning())
                   
                    // He released a key, start the timer,
                    // the timer is started after 2500ms, it sees
                    // whether the user is still in the keyReleased state
                    // which means, he is thinking
                    t.start();
                }
            });
           
            // Create a textarea
            ta=new JTextArea();
                   
            // Make it non-editable
            ta.setEditable(false);
           
            // Set some margin, for the text
            ta.setMargin(new Insets(7,7,7,7));
           
            // Set a scrollpane
            JScrollPane js=new JScrollPane(ta);
            add(js);
           
            addWindowListener(new WindowAdapter(){
                public void windowOpened(WindowEvent we)
                {
                    // Get the focus when window is opened
                    jt.requestFocus();
                }
            });
           
            setSize(400,400);
            setLocationRelativeTo(null);
            setVisible(true);
        }
       
        private void showLabel(String text)
        {
            // If text is empty return
            if(text.trim().isEmpty()) return;
           
            // Otherwise, append text with a new line
            ta.append(text+"\n");
           
            // Set textfield and label text to empty string
            jt.setText("");
            l.setText("");
        }
       
        public static void main(String args[])
        {
            SwingUtilities.invokeLater(new Runnable(){
                public void run()
                {
                    new Chatbox();
                }
            });
        }
    }

    Chat box screenshot

    Get IP address in Java using InetAddress

    The following example illustrates getting IP address in Java using InetAddress class.

    import java.net.*;
    class GetIP
    {
        public static void main(String args[]) throws Exception
        {
            InetAddress i=InetAddress.getByName(args[0]);
            System.out.println(new String(i.getHostAddress()));
        }
    }
    getByName(args[0]): This static method of InetAddress class gets the IP address of the given host name which has to be in the format, google.com for example.

    Thursday 14 November 2013

    Getting Started with JList and JComboBox

    The following tutorial illustrates getting started with two major swing components, the JList and JComboBox. The examples below provide you a basic understanding of what they are.

    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 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.

    4 JCheckBox and JRadioButton Examples for a Kickstart

    These four examples on JCheckBox and JRadioButton which cover almost all of their methods and constructors gives you a deeper understanding of them.
    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.
    1. JCheckBox Kickstart Example for Starters
    2. How to give JCheckBox a Button feel?
    3. How to add JCheckBox to JButton?
    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.
    1. JRadioButton Kickstart* Example for Starters
    Note: JButton, JToggleButton, JCheckBox and JRadioButton are all sub-classes of AbstractButton.

    3 JButton and JToggleButton Examples To Get Started

    Here are 3 examples, two on JButton and one on JToggleButton which gives you an effortless start. These examples cover almost all of the methods and constructors in these classes.
    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.
    1. Creating Buttons in Swing
    2. Complete JButton Example for Beginners
    A JToggleButton is another component much similar to a JButton. But the difference is that 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.

    2 JPanel Examples Everyone Must Learn

    Here are 2 JPanel examples that every beginner must learn.
    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. Like others this too can be customized.
    1. JPanel Example for Beginners
      This example gives you a kickstart by convering the core methods of JPanel, that are the minimum basic.
    2. Creating transparent JPanel easily
      This tiny example lets you create semi transparent JPanel in swing.

    How to read password in console in Java?

    The following illustrates reading password in console in Java which means that password isn't visible when the user is typing.

    class ReadPassword
    {
        public static void main(String args[])
        {
            System.out.println("Enter password");
           
            char[] c=System.console().readPassword();
           
            // Just print, make it simple
            System.out.println("The password is "+new String(c));
           
        }
    }
    System.console().readPassword(): The console() method generates a Console object which contains the readPassword() method. This method reads the password from the user into a char array and returns it.

    Get Season By Month and Date in Java

    The following illustrates getting season name by month and date in Java.

    import java.util.*;
    import java.text.*;
    class CheckSeason
    {
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);
           
            System.out.println("Enter the month and day");
            int m=s.nextInt();
            int d=s.nextInt();
           
           
            SimpleDateFormat f=new SimpleDateFormat("MM-dd");
            f.setLenient(false);
           
            try
            {
                Date date=f.parse(m+"-"+d);
               
                    if(date.after(f.parse("04-21")) && date.before(f.parse("06-21"))){
                        System.out.println("Spring");
                    }
                    else if(date.after(f.parse("06-20")) && (date.before(f.parse("09-23"))))
                    {
                        System.out.println("Summer");
                    }
                    else if(date.after(f.parse("09-22")) && date.before(f.parse("12-22")))
                    {
                        System.out.println("Fall");
                    }
                    else System.out.println("Winter");
            }catch(Exception e){
                System.out.println("Invalid month/date "+e);
            }
           
        }
    }
    new SimpleDateFormat("MM-dd"): Create an object for the SimpleDateFormat class of the format month-date.
    setLenient(false): Allow strict checking of the date, so that month cannot be greater than 12 and February contains no more than < 30 days always etc.
    f.parse(m+"-"+d): This creates a java.util.Date object from given month and date in the specified format.
    date.after(): This method checks if the parameter date is after the calling date, similiarily date.before() checks if the parameter date is before the calling date with the help of which we determine the season.

    How to download a file in Java?

    The following example illustrates how to download a file in Java.

    import java.net.*;
    import java.io.*;
    class DownloadFile
    {
        public static void main(String args[]) throws Exception
        {
            // Get url
            URL u=new URL(args[0]);
           
            // Open connection first
            HttpURLConnection con=(HttpURLConnection)u.openConnection();
           
            // Get the input stream pointing to the file
            InputStream fin=con.getInputStream();
           
            // Create FileOutputStream to write to a file
            FileOutputStream fout=new FileOutputStream(args[1]);
           
            int k;
           
                // Loop till end of file
                while((k=fin.read())!=-1)
                {
                    // Write each byte into file
                    fout.write(k);
                }
           
            // close all
            fin.close();
            fout.close();
        }
    }
    openConnection(): This method opens a connection to the given file.
    getInputStream(): Returns the java.io.InputStream object with which we can read data from the file and download it.

    Wednesday 13 November 2013

    8 JFrame Examples You Should Know - Swing

    JFrame is a top-level container which is nothing more than a window with a title bar and an optional menu bar.
    1. Creating a JFrame in Swing Example - A Kickstart
      This example introduces the most common methods of JFrame class.
    2. Set background color in JFrame
      You cannot set the background for a JFrame just by using the setBackground() method. This example contains the single thing you need to set the background.
    3. Set background image in JFrame
      This example shows you how to set a background image in JFrame in three ways.
    4. 3 Ways to Set Icon image for JFrame
      An icon image is the one that appears in the top-left corner of a title bar. The example will teach you three simple ways to set icon.
    5. How to create a transparent JFrame in Swing
      Opaque frames are boring. Aren't they? This example shows how to create semi-transparent JFrame easily using a simple method.
    6. Create shaped transparent JFrame in Swing
      You can also set custom shape to a JFrame but it should be undecorated. This example contains JFrames of different shapes.
    7. Using setDefaultLookAndFeelDecorated() in JFrame
      This example contains how to set the default look and feel decorated so that the titlebar's appearance changes.
    8. Double titlebar for JFrame in Swing
      Creating a double titlebar is weird but can be done in a single line!
    Well, I couldn't guarantee that these 8 JFrame examples are everything that you should know, but these cover about 95% of JFrame and give you a kickstart. There are a lot of other examples on JFrame in this blog, but as they are involved with event handling, and this is a written in an order, they aren't included.