Tuesday, October 20, 2009

Java : Simple XML Parser

/* SimpleXmlParser.java */

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document dom = null;

try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

dom = db.parse("xmlFile.xml");

//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");

if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");

Element el = (Element)nl.item(i);

System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}

public static String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}

return textVal;
}
}


/* xmlFile.xml */

<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>

Output

--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR

Friday, October 16, 2009

Java : Implement console in textarea using swing or awt

Program to implement output console using JTextArea of swing or TextArea of awt. Here all output log ie (System.out.println("")) is redirected to textarea rather than console.

Here is the complete code, directly you can run this code and see output.


/* ImplementConsole.java */


import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.io.*;

public class ImplementConsole extends JFrame
{
JTextArea console;
JScrollPane sp_console;

ImplementConsole()
{
setSize(700,350);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

console = new javax.swing.JTextArea();
console.setColumns(50);
console.setRows(15);

console.setText("Console Output...");

sp_console = new javax.swing.JScrollPane(console);

add(sp_console);

System.setOut(new PrintStream(new JTextAreaOutputStream(console)));
System.setErr(new PrintStream(new JTextAreaOutputStream(console)));


//starting new Thread for log writing
new Thread(new Runnable()
{
public void run()
{ try
{
writeLog();
}
catch (Exception ie)
{ }
}
}).start();
}

//inner class
public class JTextAreaOutputStream extends OutputStream
{
JTextArea ta;

public JTextAreaOutputStream(JTextArea t)
{
super();
ta = t;
}

public void write(int i)
{
ta.append(Character.toString((char)i));
}

public void write(char[] buf, int off, int len)
{
String s = new String(buf, off, len);
ta.append(s);
}
}


//function to write console log
public void writeLog()
{
for(int i=0; i< 10000; i++)
{
System.out.println("Console output : "+i);

// Make sure the last line is always visible
console.setCaretPosition(console.getDocument().getLength());

//just taking pause of 50ms
try
{
Thread.currentThread().sleep(50);
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}

//to flush console log after specific number of lines.
if(console.getLineCount() > 1000)
console.setText("");
}
}

public static void main(String[] args)
{
JFrame obj = new ImplementConsole();
obj.setVisible(true);
}
}



Output

Java : Time elapsed counter using swing

Java program that calculates time elapsed from start time, using this you can implement stop watch. Logic is simple just get start time (time when program started) and increment the time counter by current time minus start time ie (elapsedTime = currentTime - starTime).

Here is the complete tested code, directly you can run this code and see output.


/* TimeElapsed.java */

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class TimeElapsed extends JFrame
{
JLabel time;

long startTime = System.currentTimeMillis();

TimeElapsed()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;

String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));

if (seconds.length() < 2)
seconds = "0" + seconds;

if (minutes.length() < 2)
minutes = "0" + minutes;

if (hours.length() < 2)
hours = "0" + hours;

return hours+":"+minutes+":"+seconds;
}

public static void main(String[] args)
{
JFrame obj = new TimeElapsed();
obj.setVisible(true);
}
}



Output

Thursday, October 15, 2009

Java : Digital clock using swing

This is a simple program to implement digital clock using swing. However format of time can be modified to users desire format.

Here is the complete tested code, directly you can run this code.

/* ShowTime.java */

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class ShowTime extends JFrame
{
JLabel time;

ShowTime()
{
setSize(300,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(new SimpleDateFormat("hh:mm:ss a").format(new java.util.Date()));
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public static void main(String[] args)
{
JFrame obj = new ShowTime();
obj.setVisible(true);
}
}

Output

Java : Create Table in PDF file

Here is the program to create table in PDF file.

You need to download iText jar file to run this code. Get iText from http://www.lowagie.com/iText/download.html

Here is the complete code.

/* PDFTable.java */

import java.io.*;
import java.awt.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.Font;
// reference to Font is ambiguous
//java.awt.Font and com.lowagie.text.Font

public class PDFTable
{
public static void main(String arg[])throws Exception
{
Document document=new Document(PageSize.A4,50,10,10,10);

PdfWriter.getInstance(document,new FileOutputStream("PDFTable.pdf"));
document.open();
document.add(new Paragraph("Simple and Easy Codes"));
document.add(new Paragraph("http://simpleandeasycodes.blogspot.com/",FontFactory.getFont(FontFactory.COURIER, 14,Font.BOLD, new Color(255, 150, 200))));

Table table = new Table(3);

table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(5);

Cell cell = new Cell("header");
cell.setHeader(true);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();

cell = new Cell("example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);

table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("cell test1");

cell = new Cell("big cell");
cell.setRowspan(2);
cell.setColspan(2);

table.addCell(cell);
table.addCell("cell test2");

document.add(table);


document.close();
}
}

Monday, October 12, 2009

Java : Simple program to generate PDF File

This a simple program to generate PDF file. You need to download iText jar file to run this code. Get iText from http://www.lowagie.com/iText/download.html

Here is the complete code.

/* MyFirstPDFFile.java */

import java.io.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class MyFirstPDFFile
{
public static void main(String arg[])throws Exception
{
Document document=new Document(PageSize.A4,50,10,10,10);

PdfWriter.getInstance(document,new FileOutputStream("MyFirstPDFFile.pdf"));
document.open();
document.add(new Paragraph("Simple and Easy Codes"));
document.add(new Paragraph("http://simpleandeasycodes.blogspot.com/"));
document.close();
}
}