Friday, 20 May 2016

Digital Clock Using Thread in JAVA

Digital Clock Using Thread in JAVA

this given example is display digital clock for user it takes time from working system and display it on the JFrame with the help of thread and swing package.

Program:

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

class ClockScreen extends JFrame{
private JLabel timeString,lbl_digi;
public JButton start;
Thread t;
public ClockScreen(Thread t){
this.setTitle("Digital Clock");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200,130);
this.setLayout(null);
this.setLocation(GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x-this.getWidth()/2,GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y-this.getHeight()/2);
this.t=t;
Font font = new Font("Courier", Font.BOLD,20);
lbl_digi=new JLabel("Digital Clock");
lbl_digi.setBounds(10,10,180,20);
lbl_digi.setFont(new Font("Vardana",Font.BOLD,16));
lbl_digi.setHorizontalAlignment(JLabel.CENTER);
    lbl_digi.setVerticalAlignment(JLabel.CENTER);

timeString=new JLabel();
timeString.setBounds(10,30,180,20);
timeString.setFont(font);
timeString.setHorizontalAlignment(JLabel.CENTER);
    timeString.setVerticalAlignment(JLabel.CENTER);

start=new JButton("Stop");
start.setBounds(10,60,180,30);

start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
if(start.getText().equals("stop")){
start.setText("start");
ClockScreen.this.t=Thread.currentThread();
ClockScreen.this.t.yield();
System.out.println("jiten");
}else{
start.setText("stop");
}
}catch(Exception ex){
System.out.println("Error:"+ex.getMessage());
}
}
}); 
add(timeString);
add(lbl_digi);
add(start);
}
public void setLabelValue(String value){
timeString.setText(value);
}
}
class clock implements Runnable{
int hour,minute,second;
String strTime;
private Thread t;
private ClockScreen c1;
private String threadName;
public clock( String name){
      threadName = name;
      System.out.println("Creating " +  threadName );
c1=new ClockScreen(t);
  }
public void run() {
System.out.println("Running " +  threadName );
try {
int i=Calendar.getInstance().get(Calendar.SECOND);
while(true){
Calendar cal=Calendar.getInstance();

hour=cal.get(Calendar.HOUR_OF_DAY);

if(hour >12)
hour-=12;
minute=cal.get(Calendar.MINUTE);
second=cal.get(Calendar.SECOND);
SimpleDateFormat formatter=new SimpleDateFormat("HH:mm:ss");
Date date=cal.getTime();
strTime=formatter.format(date);
System.out.println(strTime);
System.out.println("Thread: " + threadName + ", " + second+"\t i:"+(i));
c1.setLabelValue(strTime);
/*if((second-i)>=10)
System.exit(0);*/
            Thread.sleep(1000);
        }
} catch (InterruptedException e) {
System.out.println("Thread " +  threadName + " interrupted.");
}
System.out.println("Thread " +  threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " +  threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class DigitalClock{
public static void main(String [] args){
clock c1=new clock("First");
c1.start();
}
}

run this program by following command:

<complilation>$javac DigitalClock.java
<run>$ java DigitalClock

Download Program: Click Here

output:







Monday, 16 May 2016

Reading Data From XML file in JAVA

Reading Data From XML file in JAVA

Reading of xml data from file you need to parse xml it means you need to go through xml 

Program:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class xmlReader {

  public static void main(String argv[]) {

    try {

File fXmlFile = new File("person.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Staff");
System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) 
System.out.println("First Name : " + eElement.getElementsByTagName("FirstName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("Salary").item(0).getTextContent());

}
}
    } catch (Exception e) {
e.printStackTrace();
    }
  }

}

To Run Program:
(compilation) $ javac xmlReader.java
(run) $ java xmlReader

Download Program: Click Here

Output:

Writing Data in XML file Using JAVA

Writing Data in XML file Using JAVA

DOM provides many handy classes to create XML file easily. Firstly, you have to create a Document withDocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use Transformer class to output the entire XML content to stream output, typically a File.


Download File: Click Here


Program:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.*;
import java.util.*;



public class xmlDemo{

     public static void main(String []args){
       // System.out.println("Hello World");
       Scanner userinput=new Scanner(System.in);
try{
     
         DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builder=dbFactory.newDocumentBuilder();
         
         Document doc=builder.newDocument();
         
         Element rootElement=doc.createElement("Person");
         doc.appendChild(rootElement);
         
         for(int i=0;i<5;i++){
        Element staff=doc.createElement("Staff");
        rootElement.appendChild(staff);
        
System.out.print("Enter First Name:");
String fname=userinput.nextLine();

        Element firstName=doc.createElement("FirstName");
        firstName.appendChild(doc.createTextNode(fname));
        staff.appendChild(firstName);
        
        System.out.print("Enter Last Name:");
String lname=userinput.nextLine();
        Element lastName=doc.createElement("lastName");
        lastName.appendChild(doc.createTextNode(lname));
        staff.appendChild(lastName);
        
        
        System.out.print("Enter Salary:");
String usalary=userinput.nextLine();
        Element salary=doc.createElement("Salary");
        salary.appendChild(doc.createTextNode(usalary));
        staff.appendChild(salary);
         }
         TransformerFactory transformerFactory =TransformerFactory.newInstance();
         Transformer transformer =transformerFactory.newTransformer();
//Transformer.setOutputProperty(OutputKeys.INDENT,"yes");
         DOMSource source = new DOMSource(doc);
         StreamResult result =new StreamResult(new FileWriter("person.xml"));
         transformer.transform(source, result);
         System.out.println("Xml File Write Successfully....");
        
       }catch(Exception ex){
            System.out.println("Error: "+ex.getMessage());
           
       }
     }
}


How to Run:

(compilatin) $ javac xmlDemo.java
(run) $ java xmlDemo

output: