Wednesday, June 17, 2009

Example for Runnable Interface

public class NumberPrinter implements Runnable {
int num;

public NumberPrinter(int n) {
num = n;
}

public void run() {
for (int k=0; k < 10; k++)
System.out.print(num);
} // run()
} // NumberPrinter




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

Thread number1, number2, number3, number4, number5;
// Create and start each thread
number1 = new Thread(new NumberPrinter(1)); number1.start();
number2 = new Thread(new NumberPrinter(2)); number2.start();
number3 = new Thread(new NumberPrinter(3)); number3.start();
number4 = new Thread(new NumberPrinter(4)); number4.start();
number5 = new Thread(new NumberPrinter(5)); number5.start();
} // main()
// Numbers class


}

Database Connection Jdbc with Oracle

import java.sql.*;
import javax.swing.*;

public class databaseConnection

{


public static String url,sql;
public static Connection con=null;
public static Statement stmt;



public void dbconnection()
{


try
{
url= "jdbc:odbc:information"; //database Name

String username = "system"; //Database server name
String password = "a"; //database server password

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection(url,username,password);

stmt=con.createStatement();


// JOptionPane.showMessageDialog(null,"Database is Connected");

}

catch(ClassNotFoundException ex)

{

JOptionPane.showMessageDialog(null, ex.getMessage());
System.out.println("Error connecting : \n "+ex.getMessage());


//exit if driver is not loaded.
System.exit(0);
}


catch(SQLException ce)
{

JOptionPane.showMessageDialog(null, ce.getMessage());

System.out.println(ce);
}


}


public static void main(String[] a) {

databaseConnection db=new databaseConnection();
db.dbconnection() ;


}

}

Number Validation

import java.awt.event.*;
import java.awt.*;
class NumberValid extends KeyAdapter
{
public void keyTyped(KeyEvent e)
{
char ch=e.getKeyChar();
if(ch < '0' || ch > '9')
{
Toolkit.getDefaultToolkit().beep();
e.consume();
}
}
}

Text Validation

import java.awt.event.*;
import java.awt.*;
class TextValid extends KeyAdapter
{
public void keyTyped(KeyEvent e)
{
char ch=e.getKeyChar();
if((ch >= 'a' && ch <='z')||(ch >='A' && ch <='Z'))
{
}
else
{
Toolkit.getDefaultToolkit().beep();
e.consume();
}
}
}

Login Frame with Progress bar

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


class Login1 extends JFrame
{
JButton submit,cancel,newuser;
JPanel panel1=new JPanel();
JLabel label1,label2,label3;
final JTextField text1,text2;
Container c;

PopupMenu popup = new PopupMenu();


MenuItem mItem1 = new MenuItem("Exit");
MenuItem mItem2 = new MenuItem("Minimize");
MenuItem mItem3 = new MenuItem("Maximize");

JLabel lbllogin=new JLabel(new ImageIcon("images/login.png"));
int height;
int width;
Dimension screenSize;
public Login1()

{

Toolkit kits=Toolkit.getDefaultToolkit();
screenSize=kits.getScreenSize();
width=screenSize.width/3;
height=screenSize.height/3;
setSize(width,height);
setTitle("Login Form");
setResizable(false);
setLocation(screenSize.width/3,screenSize.height/4);
setDefaultLookAndFeelDecorated(true);

setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

c=getContentPane();
panel1.setLayout(null);
JLabel l=new JLabel("Log In ");
l.setBounds(100,5,150,35);

//panel1.add(l);


popup.add(mItem1);
popup.add(mItem2);
popup.add(mItem3);


SystemTray tray = SystemTray.getSystemTray();
Image imgta = Toolkit.getDefaultToolkit().getImage("images/Home.png");
TrayIcon trayIcon = new TrayIcon(imgta,"College Inforamtion",popup);
try {
tray.add(trayIcon);
}
catch (AWTException e) {
JOptionPane.showMessageDialog(null, "Error Loading");
}


lbllogin.setBounds(260,62,53,55);
panel1.add(lbllogin);
//lbllogin.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));


label1 = new JLabel("UserName :");
text1=new JTextField();

label1.setFont(new Font("Helvetica",Font.BOLD,12));
label1.setBounds(15,60,100,25);
panel1.add(label1);
// label1.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));

text1.setBounds(120,60,120,25);
panel1.add(text1);

text1.setToolTipText("Enter UserName");
text1.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));


label2 = new JLabel();
label2.setText("Password :");

text2 = new JPasswordField();

label2.setFont(new Font("Helvetica",Font.BOLD,12));
label2.setBounds(15,90,100,25);
panel1.add(label2);
// label2.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));

text2.setBounds(120,90,120,25);
panel1.add(text2);

text2.setToolTipText("Enter Password");
text2.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));



submit=new JButton("SUBMIT");
cancel=new JButton("CANCEL");

submit.setBounds(55,130,100,25);
submit.setIcon(new ImageIcon("images/enter.png"));
panel1.add(submit);
submit.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));
submit.setFont(new Font("Lucida Regular",Font.BOLD,12));
submit.setCursor(new Cursor(Cursor.HAND_CURSOR));


cancel.setBounds(170,130,100,25);
cancel.setIcon(new ImageIcon("images/can1.png"));
panel1.add(cancel);
cancel.setBorder(BorderFactory.createBevelBorder(1,new Color(192,192,255),new Color(192,192,255)));
cancel.setFont(new Font("Lucida Regular",Font.BOLD,12));
cancel.setCursor(new Cursor(Cursor.HAND_CURSOR));

submit.addActionListener(new loginactionListener());

cancel.addActionListener(new loginactionListener());

mItem1.addActionListener(new loginactionListener());
mItem2.addActionListener(new loginactionListener());
mItem3.addActionListener(new loginactionListener());


KeyListener quickLogin = new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
if(ke.getKeyChar() == KeyEvent.VK_ENTER) {
submit.doClick();
submit.requestFocus();
}
}
};


addWindowListener(new loginWindowHandler());

submit.addKeyListener(quickLogin);

c.add(panel1);

setVisible(true);
}




class loginactionListener implements ActionListener

{
public void actionPerformed(ActionEvent ae)
{





String s = ae.getActionCommand();

if(s=="SUBMIT")
{
String u=text1.getText();
String p=text2.getText();
// System.out.println("user"+u);
//System.out.println("pass"+p);

if((u.equals("P")) && p.equals("P"))

{

SwingProgressBar swp=new SwingProgressBar();
swp.show();
dispose();



}


else{

JOptionPane.showMessageDialog(null,"Please try again");

text1.setText("");
text2.setText("");
text1.requestFocus();
}
}


if((s=="CANCEL")||(s=="Exit"))

{


int reply = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit?","Login form",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
// If the confirmation was affirmative, handle exiting.
if (reply == JOptionPane.YES_OPTION)
{

System.exit(0);
}

}

if(s=="Minimize")
{



setState(JFrame.ICONIFIED);



}

if(s=="Maximize")
{

setState(JFrame.NORMAL);

}




}



}



class loginWindowHandler implements WindowListener

{





public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e)
{

int reply = JOptionPane.showConfirmDialog(null,"Do you want to exit?","Login form",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

if (reply == JOptionPane.YES_OPTION)
{

System.exit(0);
}

}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}
public void windowActivated(WindowEvent e)

{}
public void windowOpened(WindowEvent e)
{}

}



public static void main(String arg[])


{
new Login1();



}

}


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

public class SwingProgressBar extends JFrame{
final static int interval = 1000;
int i;
JLabel label,label2,labelp;
JProgressBar pb;
Timer timer;
Timer timer2;
JButton button;
Container c;

int width,height;


Dimension screenSize;

public SwingProgressBar() {


Toolkit kits=Toolkit.getDefaultToolkit();
screenSize=kits.getScreenSize();
width=screenSize.width/3;
height=screenSize.height/3;
setSize(width,height);
setTitle("splash");
setResizable(false);
setLocation(screenSize.width/3,screenSize.height/4);
setDefaultLookAndFeelDecorated(true);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);


c=getContentPane();


UIManager.put("pb.selectionBackground", Color.black);
//UIManager.put("pb.selectionForeground", Color.white);
//UIManager.put("pb.foreground", new Color(8, 32, 128));
button = new JButton("Start");
button.setBounds(3,5,60,20);
addWindowListener(new ButtonListener());

pb = new JProgressBar(0, 20);

pb.setBounds(20,90,290,25);
pb.setValue(0);
pb.setStringPainted(true);

labelp = new JLabel();
labelp.setBounds(25,60,300,20);

label = new JLabel();
label.setBounds(25,125,300,20);

label2 = new JLabel();
label2.setBounds(25,148,300,20);

JPanel panel1 = new JPanel();
panel1.setLayout(null);

panel1.add(labelp);
panel1.add(label);
panel1.add(label2);
// panel1.add(button);
panel1.add(pb);




panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
//setContentPane(panel1);

c.add(panel1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create a timer.
timer = new Timer(interval, new ActionListener(){

public void actionPerformed(ActionEvent evt)
{
if(i<14)
{
String str2 = "" + "" + "" + " Initializing ......" + "" + "" + "";
labelp.setText(str2);
}

else if(i<17)

{
String str2 = "" + "" + "" + " Copying Files........" + "" + "" + "";
labelp.setText(str2);
}
if (i == 20){
Toolkit.getDefaultToolkit().beep();
timer.stop();

pb.setValue(0);
String str = "" + "" + "" + "System loading completed." + "" + "" + "";
labelp.setText(str);
}
i = i + 1;
pb.setValue(i);
}
});


timer2 = new Timer(interval, new ActionListener(){

public void actionPerformed(ActionEvent evt2)
{
if(i<8)
{
String str2 = "" + "" + "" + "Checking Database ......" + "" + "" + "";

String str3 = "" + "" + "" + "Checking Classes ......" + "" + "" + "";
label.setText(str2);
label2.setText(str3);
}

else if(i<13)

{
String str3 = "" + "" + "" + " Loading Database ......" + "" + "" + "";

String str4 = "" + "" + "" + " Loading Classes ......" + "" + "" + "";
label.setText(str3);
label2.setText(str4);
}

else if (i <18)
{
String str3 = "" + "" + "" + " Loading Application......" + "" + "" + "";

String str4 = "" + "" + "" + " Thank you for using this application ......" + "" + "" + "";
label.setText(str3);
label2.setText(str4);

}




i = i + 1;

}
});



}


class ButtonListener implements WindowListener {
public void windowActivated(WindowEvent ae) {



timer.start();
timer2.start();
}



public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e)
{}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowOpened(WindowEvent e)
{}

}

/* public static void main(String[] args) {
SwingProgressBar spb = new SwingProgressBar();

spb.setVisible(true);

}*/
}




Monday, June 15, 2009

Format of Input

import java.io.Console;
import java.lang.String;
import java.io.IOException;



public class input1 {

public static void main (String args[]) throws IOException {

Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String login = c.readLine("Enter your login: ");
String n=console.readline("enter age");

System.out.print("name is",login);
c.format("name is %s",login);
c.format("name is %s",n);
}
}

Example for instanceof

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

Parent obj1 = new Parent();
Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));
}
}

class Parent{}
class Child extends Parent implements MyInterface{}
interface MyInterface{}

ReverseString

public class ReverseStringTest {
public static void main(String[] args) {
String str = "What's going on?";
System.out.println(ReverseString.reverseIt(str));
}
}

class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);

for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}

Example of Garbage Collection

import java.io.*;
import java.lang.*;
class GC
{
public static void main(String s[])
{
Runtime r=Runtime.getRuntime();
System.out.println("Total Memory:" +r.totalMemory());
System.out.println("Free Momery before allocation:" +r.freeMemory());
String str[] = new String[20];

for(int i=0;i<20;i++)
{
str[i]=new String("String Object No. "+i);
System.out.println(str[i]);
}
System.out.println("Free Momery after allocation:" +r.freeMemory());
for(int i=0;i<20;i++)
str[i]=null;
r.gc();
System.out.println("Free Momery after Garbage Collection:" +r.freeMemory());
}
}

Simple Frame

import java.awt.*;

public class FrameExample{
Frame f;

public FrameExample(){
f=new Frame("Hello ");
}
public void launchFrame(){
f.setSize(400,170);
f.setBackground(Color.blue);
f.setVisible(true);
}
public static void main(String args[]){
FrameExample guiwindow=new FrameExample();
guiwindow.launchFrame();