Monday, November 18, 2013

Splash Screen

Splash screen is a special window that displays in a short time period before the main window of a program or website shows. Generally, on the splash screen, you will see an image that represents an introduction to the program or website. Sometimes, a splash screen displays a progress bar to inform the user about a process that is loading and might take a long time to complete. When the process completes, the splash screen disappears.

In Java, you can use the SplashScreen class (in awt package) to create a splash screen for your program. Alternatively, you can write your own code to create a splash screen. In this tutorial, i prefer to do the latter. First of all, you will have a class that extends the JFrame class. This class will represent the splash screen. In this tutorial, i name it as SimpleSplashScreen. The splash screen has no border and title. So will use the setUndecorated method to hide border and title. On the splash screen, there is an image that provides introductory information of the program. The JLabel component is used to wrap the image. Then it will be added on the splash screen to show the image. In the SimpleSplashScreen class, you need to add two methods. The first method (wait) allows the user to set the time delay of the splash screen. Another method (showScreen) will be invoked in the program to display the splash screen. Simply, when the time is out, the splash screen disappears and the Welcome window is shown.

splash screen

welcome


This is the complete code of the SplashScreen program.

import java.awt.Container;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class SimpleSplashScreen extends JFrame{
int delay=2000; //default delay time 2 seconds
SimpleSplashScreen(String imgfile){
ImageIcon iicon=new ImageIcon(imgfile);
int iwidth=iicon.getIconWidth();
int iheight=iicon.getIconHeight();
setSize(iwidth,iheight);
setLocationRelativeTo(null);
setUndecorated(true);
Container cont=getContentPane();
JLabel lbl=new JLabel();
lbl.setIcon(iicon);
cont.add(lbl);
}
//set time delay
public void wait(int mills){
delay=mills;
}

public void showScreen(){
setVisible(true); //show the screen
try {
Thread.sleep(delay); //delay the screen
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//close the SplashScreen when time out
dispose();
new MaiInterface();
}
}

class MaiInterface extends JFrame{
MaiInterface(){
setSize(400,300);
setTitle("Your main interface here");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont=getContentPane();
JLabel lbl=new JLabel("Welcome");
lbl.setHorizontalAlignment(JLabel.CENTER);
lbl.setFont(new Font("Arial", Font.BOLD,30));
cont.add(lbl);
setVisible(true);
}
}
public class SplashSr {
public static void main(String[] args){
SimpleSplashScreen sss=new SimpleSplashScreen("d:/splashscreen.png");
sss.wait(5000);
sss.showScreen();
}
}

Saturday, November 16, 2013

Open browser with Desktop class

Desktop is a useful class in Java. It can be used to open the default browser for a specified url, open a default mail client with optional e-mail address, open a file for editing or viewing, and send a file to the default printer.
To do such operatons mentioned above, first you need to create an object of the Desktop class by using the getDesktop method.

Desktop dt=Desktop.getDesktop();

To launch the default browser on your computer with a specified url, you will use the browse method. The browse method has one argument that is a uri object referencing to the url. To obtain the uri object, you have to create a url object that accepts the address of a web page. Then use the toURI method to convert the url object to uri object. The example code below will open the default browser and shows the http://javatheprogram.blogspot.com address on its address box.


open browser


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

public class DesktopDemo {

public static void main(String args[]){
//openMail();
try {

URL url=new URL("http://javatheprogram.blogspot.com");
openBrowser(url.toURI());

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//openFile("d:/chart.pdf");

}


public static void openBrowser(URI uri){
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
try {

dt.browse(uri);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

You can launch an e-mail client program with your specified e-mail address by using the mail method. The mail method accepts one value that is the uri object. When you construct an url object to refer to an e-mail address, the string that will be passed to the URL constructor takes this form: "mailto:e-mail_addresss". The example below will open the e-mail client program with the e-mail address yuk.dara@gmail.com on you machine.

public static void openMail(){
try {
URL url=new URL("mailto:yuk.dara@gmail.com");
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.mail(url.toURI());
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

To open a file on your local computer, you will use the open method. This method will take the file object that references to a file on your computer. The code below opens the test.txt file (in drive D) of the computer.

dt.open(new File("d://test.txt"));

If you wan to print the file to the default printer that connects to your computer, you can use the print method. This method also accepts the file object that you want to print. The following code will print the file chart.pdf to the default printer.

dt.print(new File("d:/chart.pdf"));

Tuesday, November 12, 2013

Robot in Java

Robot is an automation class in AWT package of Java. The Robot class is useful when your Java programs requires test automation, mouse, and keyboard controls. The frequently used methods of the Robot class are shown in the table below.

Method Description
createScreenCapture(Rectangle r) This method returns the image (BufferedImage object) of the captured screen. The dimension of the image is specified by the rectangle r argument.
delay(int mills) The delay method will delay the robot before an event occurs.
getPixelColor(int x,int y) The getPixelColor returns the color at the specified coordinate (x,y) on the screen.
keyPress(int key) This method tells the robot to press a key specified by the key argument. The KeyEvent class defines key constants that can be used in this method.
mouseMove(int x,int y) The mouseMove method will move the mouse pointer to the coordinate (x,y) on the screen.
mousePress(int buttons) This method tells the robot to press the mouse button. The value of buttons argument can be found in the InputEvent class.

In the example code below, the robot is commanded to move to the start button on the Task Bar of Window 7 and the mouse is clicked there. Then the word notepad are typed in the search box and the Enter key is pressed to open the NotePad application.

public class RobotDemo {
public static void main(String[] args){
try {
Robot r=new Robot();
//move to the start button on the Task Bar
r.mouseMove(20, (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
r.mousePress(InputEvent.BUTTON1_MASK); //press the left button
//type notepad in the search box
r.keyPress(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_O);
r.keyPress(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_D);
//delay the key pressed
r.delay(1000);
//press enter key
r.keyPress(KeyEvent.VK_ENTER);

} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}


Another example is an easy screen capture program. To capture any part of the screen, you will drag the transparent capturing rectangle to a location on the screen where you want to capture. Then press the Enter key to capture the screen. In default, the captured area is 400 pixels wide (width) and 300 pixels long (height). If you wan to increase the dimension of the area to be captured, you will press the ] symbol key. Similarly, to decrease the dimension, simply press the [ symbol key. To minimize the transparent capturing rectangle, press the minus (-) key. When your work completes, you can press the ESC key to exit the program.
The images of the captured screen are saved in the current working directory of the program.

Robot screen capture



import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;

class InUI extends JFrame{
int wWin;
int hWin;
int xWin;
int yWin;
InUI(){

wWin=400;
hWin=300;
setSize(wWin,hWin);
Point loc=MouseInfo.getPointerInfo().getLocation();
xWin=loc.x;
yWin=loc.y;
setLocation(xWin,yWin);
addKeyListener(new KeyDetector());
addMouseMotionListener(new MouseMove());
setUndecorated(true);
setOpacity(0.7f);
Container cont=getContentPane();
cont.setLayout(new BorderLayout());
JLabel lbl=new JLabel("<html>Click and drag this capture area.<br>Press Enter to capture the screen.</html>");
lbl.setHorizontalAlignment(JLabel.CENTER);
cont.add(lbl, BorderLayout.CENTER);
setVisible(true);

}

class KeyDetector extends KeyAdapter{
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyCode());
int code=e.getKeyCode();
if(code==27) //exit the program when the Esc key is pressed. 
System.exit(0);
else if(code==45) //minimize the capture
minimize();
else if(code==91) //decrease capture area
decreaseSize();
else if(code==93) //increase capture area
increaseSize();
else if(code==10){ //capture the screen when Enter key is pressed
minimize();
capture();
}
//else if((code==KeyEvent.VK_X) && (e.getModifiers() & KeyEvent.ALT_MASK)!=0 )
//System.exit(0);

}
}
class MouseMove extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e){
//change location of the capture area when mouse is dragged
setWinLocation(e.getXOnScreen(),e.getYOnScreen());
}
}
public void increaseSize(){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
if(wWin<ds.getWidth()){
wWin+=5;
this.setSize(wWin,hWin);
}
if(hWin<ds.getHeight()){
hWin+=5;
this.setSize(wWin,hWin);
}

}
public void decreaseSize(){
if(wWin>5){
wWin-=5;
this.setSize(wWin,hWin);
}
if(hWin>5){
hWin-=5;
this.setSize(wWin,hWin);
}
}
public void setWinLocation(int x,int y){
xWin=x-wWin/2;
yWin=y-wWin/2;
this.setLocation(new Point(xWin,yWin));
}
public void minimize(){
this.setExtendedState(JFrame.ICONIFIED);
}
public void capture(){
try {
Robot rb=new Robot();
//capture the target part of the screen
BufferedImage bi=rb.createScreenCapture(new Rectangle(xWin,yWin,wWin,hWin));
//save the image
ImageIO.write(bi, "png", new File(System.getProperty("user.dir")+File.separator+"image"+System.currentTimeMillis()+".png"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

public class RobotDemo {
public static void main(String[] args){
new InUI();
   }
}

Monday, November 11, 2013

final class, variable, and method

Java does allow you to extend a class, change the value of a variable, and override a method of a class. Sometimes, however, you can modify this behavior to disable extendibility, prevent value of the variable from being changed, and prevent the method from being overridden by using the final keyword.

When the final keyword is written before the name of a class, the class will become a final class. You cannot create a sub-class to extend the final class. You will get a compile error if you try to extend the final class. By placing the final keyword before the name of a variable, the variable will be a constant variable. You can assign a value to the constant variable only one time when it is defined. Further change to the value of the variable will also generate compile error. When the final keyword stays before the name of a method, the method will become a final method. The final method does not allow any code to override it.

In the example code below, the Reader class is a final class. The value of the path variable cannot be further changed by any code in the class. The readText method can be called from other classes. However, it cannot be overridden by any code outside the class.

import java.io.BufferedReader;
import java.io.FileReader;

final class Reader{ //final class
private final String path="d:/test.txt"; //constant variable

public final void readText(){ //final method
try {
FileReader fr=new FileReader(path);
BufferedReader br=new BufferedReader(fr);
String content="";
while((content=br.readLine())!=null){
System.out.println(content);
}
br.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

If you try to extend the Reader by creating another class and use the extends keyword, the compile error will display as shown in the picture below.

final keyword

Thursday, November 7, 2013

Generics

Generics is a powerful feature in Java programming language. It is implemented in Collections Framework of Java. The Generics allows you to create generic class, interface, method, and variable. A generic class, interface, method, or variable can work with different types of data because you can specify the type of data as a parameter. Since the generic class, interface, method, or variable does not restrict the type of data when it is defined, it can be reused. For example, you can create only a LinkedList class to store text, integer values, or floating-point values.
You can create a generic class or interface by placing the generic type parameter between the smaller and the greater signs (< and >) after name of the class. The example code below creates a generic class called ListNode. T is the generic type parameter. When you define a generic method or variable, you can place the generic type parameter as you do with a normal data type. This generic type parameter must be the same as the generic type parameter defined with the class.

Example:

class ListNode<T>
{
  public T val;
  public ListNode<T> next;
  public ListNode(T val) { this.val = val; next = null; }

}

When you use a generic class to store value by creating an object and pass the value to it, you should specify the specific data type of the value.

Example:

ListNote<Integer> node=new ListNode<Integer>(123);

You can use many generic type parameters in a class, interface, or methods. You will need to separate the type parameters by comma. See the example below.
Example:

class MyMap<T1,T2>{
  private T1 key;
  private T2 value;
  MyMap(T1 key, T2 value){
    this.key=key;
    this.value=value;
  }
}


Here is the complete LinkedList program that uses the Generics feature.

class ListNode<T>
    {
        public T val;
        public ListNode<T> next;
        public ListNode(T val) { this.val =val; next = null; }
       

    }

interface ListOperations<T>
    {
        void insertNode(T val, int post);
        void deleteNode(int post);
        void printList();
       
    }
class LinkedList<T> implements ListOperations<T>

{
    protected ListNode<T> pfirst; //pfirst points to the first element of the linked list
    protected ListNode<T> plast;//plast points to the last element of the linked list
    protected int NumItems;
    public LinkedList() { pfirst = plast = null; NumItems = 0; }
    
    public void insertNode(T val,int post)
    {
        ListNode<T> newNode = new ListNode<T>(val);
        if (pfirst == null)
        {
            pfirst = newNode;
            plast = newNode;
            NumItems++;

        }
        else
        {
            if (post == 1)
            {
                newNode.next = pfirst;
                pfirst =newNode;
                NumItems++;
            }

            else if(post>1 && post<=NumItems){
                ListNode<T> ta = pfirst;
                for (int i = 1; i < post - 1; i++) ta = ta.next;
                newNode.next = ta.next;
                ta.next = newNode;
                NumItems++;
            }
            else if (post == (NumItems + 1))
            {
                plast.next = newNode;
                plast = newNode;
                NumItems++;
            }
            else
            {
                System.out.println("Invalid position");

            }


        }

    }
    public void deleteNode(int post)
    {
        if (pfirst == null)
        {
        System.out.println("Empty list");
            return;
        }

        if (post == 1)
        {
            if (NumItems == 1)
            {
                pfirst = null;
                plast = null;
            }
            else
            {
                ListNode<T> temp = pfirst;
                pfirst = pfirst.next;
                temp = null;
            }
        }
        else if(post>=1 && post<=NumItems){
            ListNode<T> temp, ta;
            ta = pfirst;
            for(int i=0;i<post-1;i++) ta=ta.next;
            temp = ta.next;
            ta.next = temp.next;
            if (temp.next == null) plast = ta;
            temp = null;
        }

    }
    public void printList()
    {
        ListNode<T> ta = pfirst;
        while (ta != null)
        {
        System.out.println(ta.val);
            ta = ta.next;
        }
    }
    
    

public Object[] toArray(){

  Object[] arr=new Object[NumItems];
  ListNode<T> ta = pfirst;
  int i=0;
       while (ta != null)
       {
          arr[i]=ta.val;
           ta = ta.next;
           i++;
       }
       
       return arr;
  
   }
   

}



public class GenericsJava {
public static void main(String[] args){
//Creating linked list to store text
LinkedList<String> lstString = new LinkedList<String>();
lstString.insertNode("Item1", 1);
lstString.insertNode("Item2", 2);
lstString.insertNode("Item3", 3);
lstString.printList();
//creating linked list to store numbers
LinkedList<Integer> lstNumber = new LinkedList<Integer>();
lstNumber.insertNode(10, 1);
lstNumber.insertNode(13, 2);
lstNumber.insertNode(13, 3);
lstNumber.printList();

}


}

Tuesday, November 5, 2013

GridBagLayout

GridBagLayout is a layout manager in AWT package. It is more complex than GridLayout. But it is more powerful or flexible than GridLayout. By using the GridBagLayout, you can have different components of different sizes in a single row or column. When you arrange components on a container, you do not need to specify the number of rows or columns. Instead, you will need to specify the constraints or rules by using the GridBagContraints class. These constraints help GridBagLayout to place the components in the proper places on the container. Below are common constraints used in setting up the grid.

fill allows the components to resize automatically when the row or column expanded or thrinked.
gridwidth specifies the number of columns in the area to display the component.
gridheight specifies the number of rows in the area to display the component.
gridx specifies the column in the grid to display the component. Its value starts from 0 (first column).
gridy specifies the row in the grid to display the component. Its value starts from 0 (first row).


Example: The following code below arranges the components on the JFrame window as shown in the picture.

GridBagLayout


import java.awt.Container;
import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;


public class GridBagLayoutManager {
public static void main(String[] args){
JFrame jf=new JFrame("GridBagLayout");
jf.setSize(500,300);
Container container=jf.getContentPane();
GridBagLayout gb=new GridBagLayout();
container.setLayout(gb);
GridBagConstraints gc = new GridBagConstraints();
JButton bt1=new JButton("Button 1");
JButton bt2=new JButton("Button 2");
//fill components in cells
gc.fill = GridBagConstraints.BOTH;
        gb.setConstraints(bt1, gc);
        gc.gridwidth = GridBagConstraints.REMAINDER;
        gb.setConstraints(bt2, gc);
      container.add(bt1);
container.add(bt2);

//add JTextArea, Button 3, and Button 4 to the second row

JTextArea ja=new JTextArea(10,10);
ja.setLineWrap(true);
ja.setText("GridBagLayout is a layout manager that is more powerful than the GridLayout manager.");
JButton bt3=new JButton("Button 3");
JButton bt4=new JButton("Button 4");
//expand row and column
gc.gridwidth =2; //2 columns
gc.gridheight =3;//3 rows      
gb.setConstraints(ja, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
//reset row and column
gc.gridwidth =1;
gc.gridheight = 1;
gb.setConstraints(bt3, gc);
gc.gridy=2; //Add the Button 4 below the Button 3
gb.setConstraints(bt4, gc);
container.add(ja);
container.add(bt3);
container.add(bt4);


jf.setVisible(true);

}


}


Sunday, November 3, 2013

ArrayDeque

ArrayDeque is a data structure that implements the Deque interface. Deque is the short form of "double ended queue" and generally pronounced as "deck". The ArrayDeque does not limit the number of its elements. It can grow when needed. It is likely to be faster than stack or queue data structure when it used as stack or queue data structure. Most its methods (e.g. add, addFirst, addLast, clear, clone, getFirst, getLast, isEmpty, peekFirst, peakLas, pollFirst, pollLast, size, and toArray) of the ArrayDeque run in constant time (c) and few methods (e.g. remove, removeFirstOccurence, removeLastOccurrence, and contains) run in linear time (O(n)). You can create an ArrayDeque object by using one of the ArrayDeque constructors.

-ArrayDeque() creates an empty deque enough for storing 16 elements.
-ArrayDeque(Collection<? extends E> c) creates a deque from a specified collection object (e.g. ArrayDeque, LinkedList, Stack, ...).
-ArrayDeque(int capacity) creates an empty deque with initial capacity (number of elements).

To add a new element to the ArrayDeque object, you can use the add(E e), addFirst(E e), and addLast(E e) methods. The add and addLast method will add the element at the end of the deque. The addFirst method will add the element to the front of the deque.

Example:

ArrayDeque<Integer> ad=new ArrayDeque<Integer>();
Random random=new Random();
for(int i=0;i<10;i++){
   ad.add(1+Math.abs(random.nextInt())%6);
}

To remove elements from the ArrayDeque object, you will use the clear, poll, pollFirst, pollLast, remove, remove(Object o), removeFirst(), removeFirstOccurence(Object o), removeLast, and removeLastOccurrence (Object o). The clear method will remove all elements of the deque. The poll, pollFirst, remove, removeFirst methods will retrieve and remove the first element of the deque. The pollLast and removeLast method will retrieve and remove the last elelement of the deque. If you want to remove any element in the deque, you can use the remove(Object o) method. The removeFirstOccurrence will remove the the first matched element and the removeLastOccurrence will remove the last matched elements.

Example:

int fele=ad.remove();
System.out.println("Removed "+fele);
int lele=ad.removeLast();
System.out.println("Removed "+lele);

If you want to get the elements without removing them from the deque, you will use the getFirst, getLast, peekFirst, and peekLast methods. The getFirst and peekFirst methods return the first element of the deque. In contrast, the getLast and peekLast methods return the last element of the deque.

Example:

int fele=ad.getFirst();
System.out.println("The first element is "+fele+".");
int lele=ad.getLast();
System.out.println("The last element is "+lele+".");
Another useful method of the ArrayDeque is iterator(). The iterator method can be used traverse through the deque. See the example code below.

Iterator<Integer> i=ad.iterator();
while(i.hasNext()){
   System.out.print(i.next()+"\t");

}

Saturday, November 2, 2013

Get IP Address

In Java, it is not hard to get the IP address or host name of the local or remote machine. If your program has to retrieve the IP address or host name of a machine, you will use the InetAddress class. The instance of the InetAddress stores IP address and host name of the machine. The getLoopbackAddress method of the InetAddress will return the loop back address and the localhost name of the local machine. These information are embedded in an InetAddress object. Besides getLoopbackAddress method, you can use the getLocalHost method to get the IP address and the host name that you use to connect to your network. See the example code below.

import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

public class GetIP{
public static void main(String[] args) {
   try
    {

        InetAddress addr1 = InetAddress.getLoopbackAddress();
        InetAddress addr2 = InetAddress.getLocalHost();
        System.out.println("Host name:"+addr1.getHostName());
        System.out.println("IP:"+addr1.getHostAddress());
        System.out.println("Host name:"+addr2.getHostName());
        System.out.println("IP:"+addr2.getHostAddress());
        
        
           }catch(UnknownHostException e) {e.printStackTrace(); }

}
}


get local and remote machine IP address




The two methods above are able to get the IP addresses and host names of the local machine only. If you want to get the IP addresses of a remote machine (e.g. IP addresses of a web server), you will use the getByName method. This method accepts the host name of the remote machine. You will use the URL class to point to the remote host.

public static void getIPfromURL(String strurl){
try {
URL url=new URL(strurl);
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.getHostAddress());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}