Sunday, December 22, 2013

Applet application

Besides, desktop applications that run on operating systems, Java allows you to create applications that can be run on web browsers that enable Java or applet viewers. These types of applications are called applet applications. The java.applet package has Applet class that provides necessary support for applet applications.

Unlike desktop or stand-alone application, applet does not require the main method. The execution of the applet does not begin at the main method. Rather, Applet class provides different methods serving as the basic mechanism of executing an applet application on a web browser or applet viewer. These methods are init(), start(), paint(), stop(), and destroy(). When an applet begins, the init() methods is called. You can use this method to initialize variables. The init() method is called once. The start() method is called after the init() method. This method is called every time the applet's HTML page displays on the web browser. When the user leaves the HTML page that contains applet, the applet stops by calling the stop() method. When he/she comes back to that page, the start() method will be called again to resume the applet. The destroy() method will be called after the stop method to free up resources used by applet from memory. The paint method is called each time the applet needs to redraw its output. For example, the applet draw its output when it starts and it is minimized and restored.

Create an applet

To create an applet application, you will extend the Applet class in java.applet package. The following example code is a simple applet application to display an image and a button that can be clicked to change the background color of the applet's window. You need an image file called gmaptr.png.

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
/* 
<applet code="AppletApp" width=600 height=300> 
</applet> 
*/

public class AppletApp extends Applet implements ActionListener{

public void init(){
setSize(600,300);
setBackground(Color.LIGHT_GRAY);
Button bt=new Button("Change Color");
bt.setBackground(Color.PINK);
bt.addActionListener(this);
add(bt);

}

public void paint(Graphics g){
try {
MediaTracker mt=new MediaTracker(this);
URL imgurl=new URL(getCodeBase().toString()+"gmaptr.png");
Image img=getImage(imgurl);
mt.addImage(img,0);
mt.waitForID(0);
g.drawImage(img,10, 10,this);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showStatus("There are one button and one image on the applet window.");
}

public void actionPerformed(ActionEvent e){
Color c=getBackground();
if(c==Color.BLACK)
setBackground(Color.BLUE);
else

setBackground(Color.BLACK);
}
}


You need to create AppletApp.class file from the source code above. This can be done by compiling the source code with the javac command from command prompt.

Embed the applet in HTML file

In order to execute the applet on a web browser, you need to create an HTML file that includes the applet. You can include the applet within the HTML document by using the <applet> tag. Below is an example HTML file.

<!DOCTYPE html>
<html>
<head> <title>Applet Test</title>
</head>
<body>
<applet code="AppletApp" width=600 height=300>
</applet>
</body>

</html>

After you create the HTML file that contains applet, you can execute the applet by using the appletviewer tool that comes with JDK. The command line below will execute the AppletApp application in the appletviewer from command prompt.

D:\sitedemo\AppletApp\AppletTest\bin>appletviewer AppletApp.html


run applet from command prompt


If you are Eclipse user, you can execute the applet in the appletviewer from Eclipse by clicking the Run menu item.
Besides running the applet from command prompt and Eclipse, you can run the applet in a web browser that supports Java. You need to copy the AppleAppt.class, AppletApp.html, and other related files to a directory of your web server. Then run the HTML file as you do with other HTML, php, or jsp pages. In my machine i have Chrome browser and WampServer installed.


run applet from web browser


Thursday, December 5, 2013

XML processing in Java

XML and HTML are Markup Languages. However, they are different. XML is generally used to store and transport structured data while HTML is used to format and present the data. Today XML is the most common tool for data transmissions on the web. In XML file, you can define your own tags or elements starting from a root tag and then its children tags. Here is an example of an XML file:

xml file example


The root element is Books. Under the root element, there are two sub-elements or children elements Book.

This tutorial is designed for people who come to work with XML file in Java. After completing the tutorial, you will be able to create an XML document and save it to a file, read data from an XML file, and modify elements in the XML file by using JDOM library. With the JDOM libary, XML file can be easily created, read, and modified.

Create XML document and Save it to a file

To create an XML document, first you will use the Element class to create a root element object. Then create a document object by using the Document class to wrap the root object. A child element object can also be constructed by using the Element class and added to root element by using the addContent method. You can add many children to the root element. To save the XML document to a file, you will use the XMLOutputter class. The XMLOutputter class has a method called output that can be used to write the document to the file.  See the example code below:

public static void createXML(){
//create a root element
Element root=new Element("Books");
//construct the document object with the root
Document doc=new Document(new Element("Books"));
//create first child element
Element b1=new Element("Book");
b1.setAttribute("Title","C++ for beginners");
b1.addContent(new Element("Author").setText("Dara"));
b1.addContent(new Element("Year").setText("2011"));
//add the first child to the root
root.addContent(b1);

//create second child element
Element b2=new Element("Book");
b2.setAttribute("Title","Java for programmers");
b2.addContent(new Element("Author").setText("Dara"));
b2.addContent(new Element("Year").setText("2012"));
//add the second child to the root
root.addContent(b2);
//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(doc, new FileWriter("d:/books.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Read data from the XML file

Reading data from an XML file is a common task. This task can be accomplished easily by using JDOM. To read the data from the XML file, you will use SAXBuilder class to construct a document object from the XML file. After you have the document object, you can easily navigate through the document to access all its elements. Read the example code below:


public static void readXML(){
SAXBuilder builder=new SAXBuilder();
try {
//construct document object from the file books.xml
Document doc = (Document)builder.build(new File("d:/books.xml"));
//get the root element
Element root=doc.getRootElement();
//get all children of the root
List<Element> chs=root.getChildren();
for(Element e: chs){
System.out.println("Book:");
System.out.println("\t"+e.getChild("Author").getText());
System.out.println("\t"+e.getChild("Year").getText());
}

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

}

Modify the data in the XML file

Before you can modify the data in the XML file, first you need to read the XML file in to a document object as you did in the previous section. Then you can add new children elements to the root, update data of an element, or delete an element from the document. After you complete the tasks, call the output method of the XMLOutputter class to save change to the file. Here is the example code.

public static void ModifyXML(){
SAXBuilder builder=new SAXBuilder();
try {
Document doc = (Document)builder.build(new File("d:/books.xml"));
Element root=doc.getRootElement();
//create third child element
Element b3=new Element("Book");
b3.setAttribute("Title","C# for beginners");
b3.addContent(new Element("Author").setText("Dara"));
b3.addContent(new Element("Year").setText("2013"));

//add the third child to the root
root.addContent(b3);

//Update the year of a book
List<Element> chs=root.getChildren();
for(Element e: chs){
Element ce=e.getChild("Year");
if(ce.getText().equals("2013")){
ce.setText("2010");
break;
}
}
//Remove a book that has the title "C# for beginners"
for(Element e: chs){
if(e.getAttribute("Title").getValue().endsWith("C# for beginners")){
root.removeContent(e);
break;
}

}

//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("d:/books.xml"));

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

compass app flashLight app