Thursday, September 30, 2010

A nice site.....


Found a nice site today::
www.typealyzer.com
They analyze your blog and tell you who you are. According to them, I am:
ISTP - The Mechanics
The independent and problem-solving type. They are especially attuned to the demands of the moment and are highly skilled at seeing and fixing what needs to be fixed. They generally prefer to think things out for themselves and often avoid inter-personal conflicts.

The Mechanics enjoy working together with other independent and highly skilled people and often like seek fun and action both in their work and personal life. They enjoy adventure and risk such as in driving race cars or working as policemen and firefighters.......

Intelligent Catch Block

A new Feature in jdk1.7....
Use just one catch instead of two unless needed.......

Suppose you are writing a program that interact with SQL and do some IO,suppose your program can throw SQLException and IOException...
Now you know that,you have to keep separate catch Blocks to catch the Exception thrown by the different hierarchy Classes as in our case IOException and SQL Exception...

so we have to write
try
{
//some code that can throw IO or SQL Exception
}
catch(IOException e)
{
//so some work
}
catch(Exception e)
{
//do same work
}

as we can see we have to perform the same task independent of the Exception type,but still we have to keep two catch blocks ..that is the code is lengthy as well as redundant.....
so to solve this problem sun came with a solution and the solution is just a Operator Yes...the same old bitwise OR operator(|)...

now we can catch the Exceptions in one catch block using Bitwise OR operator...
so we will say::

try
{
//some code that can throw IO or SQL Exception
}
catch(final IOException | SQLException e)
{
//handle the ecxeption
}

Caution::but keep in mind....that 'e' must be final.........

No more equals...just switch

Just remove one restriction from your mind that only the legal argument type of a switch statement is int, or any other type that can be promoted to int: byte, short, or char.
Now with the jdk1.7 it can be a String also......a big overhead of using equals have been solved by sun....

OverHead with equals::
String cmd="your string";
if(cmd.equals("dir"))
showDir();
else if(cmd.equals("cls"))
clearScreen();
else if(cmd.equals("exit"))
exitFrom();
else
goToHell();

a big overhead of if/else ladder and all,
a lenghty code,
but now leave the clumpsy else-if ladder
just switch to "switch"

String cmd="your string";
switch(cmd)
{
case "dir":
showDir();
break;
case "cls":
clearScreen();
break;
case "exit":
exitFrom();
break;
default: //the beauty of switch
goToHell();
}

Friday, September 24, 2010

2 power 99999

import java.math.BigInteger;
class Power
{
public static void main(String... s)
{
BigInteger i1=new BigInteger("2");
System.out.println(i1.pow(99999));
}
}

Download

Sudoku

//By Er. Minal Bansal
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Logic {

//to start with a random index y of array 1 to 9
Random ranobj=new Random();
int y=ranobj.nextInt(9);

// this is final array
int arr[][]=new int[9][9];
int myarray[]=new int[9];

// i,j -> indices of array arr
//k -> index of arr upto which elements are not added
int i=0,j=0,k=8;

//flag1 is false if this element cannot be added
boolean flag1=true;

//elements to be added
int next[]={1,2,3,4,5,6,7,8,9};

Logic() {
firstRow();
fill();
}

public void firstRow() {

do {

//for every new element
flag1=true;
int x=next[y];

//check in row
if(flag1) {
for(int jprev=0;jprevif(arr[i][jprev]==x) { flag1=false; }
}
}

//if element can be added
if(flag1) {

myarray[j]=x;
j++;

//shift forward elements
for(int t=y;tnext[t]=next[t+1];
}

k--;
}

//take next element from this location
y=y+j;
if(y>k) { y=0; }

//repeat until all rows are not covered
}while(j<9);

} // firstRow

public void fill() {

int p,count,m,n=0;
//arrangement
int loc[][]={ {0,1,2,3,4,5,6,7,8},{3,4,5,6,7,8,0,1,2},{6,7,8,0,1,2,3,4,5} };

for(i=0,m=0;i<9;i++,m++) {

if(m%3==0) { m=0; }
if(i>2) { n=1; }
if(i>5) { n=2; }

for(j=0;j<9;j++,n++) {

if(n==9) { n=0; }

arr[i][j]=myarray[loc[m][n]];
} // for n

} // for m

} // fill

} //logic class

public class Design extends Logic implements KeyListener,MouseListener,Runnable
{
private JFrame myframe;
private JTextField txt[][]=new JTextField[9][9];
private JPanel pcenter,pnorth,p[]=new JPanel[9];
private JMenuBar menubar;
private JMenu game,help;
private JMenuItem newgame,restart,check,submit,exit,what,option,myself;
private int mychoice=3;
private boolean myflag=false;
private int row=0,column=0;
private java.util.Timer timer = new java.util.Timer();
private JLabel l1=new JLabel(),l2 = new JLabel(),l3 = new JLabel(),l4 = new JLabel(),l5 = new JLabel();
private static Thread t;

Design()
{
initialize();
}

private void initialize()
{

for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
txt[i][j]=new JTextField();
txt[i][j].setHorizontalAlignment(JTextField.CENTER);
txt[i][j].setBackground(Color.yellow);
txt[i][j].setFont(new Font("Verdana",Font.BOLD,25));
txt[i][j].setText(String.valueOf(arr[i][j]));
txt[i][j].setEditable(false);
txt[i][j].addKeyListener(this);
txt[i][j].addMouseListener(this);
}
}

for(int i=0;i<9;i++)
{
p[i]=new JPanel();
p[i].setBackground(Color.green);
p[i].setLayout(new GridLayout(3,3,2,2));
}

for(int m=0;m<9;m++)
{

int i=0,x=0,y=0,z=0;

if(m>0) { x=m; }
if(m>2) { x=m-3; }
if(m>5) { x=m-6; }
y=x*3;

if(m<9) { i=6; }
if(m<6) { i=3; }
if(m<3) { i=0; }
z=i+3;

for(;i{
for(int j=y;j{
p[m].add(txt[i][j]);
}
}
}

newgame=new JMenuItem("New game");
newgame.addActionListener(new MyMenuHandler1());
newgame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_MASK));

restart=new JMenuItem("Restart this game");
restart.addActionListener(new MyMenuHandler2());
restart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,KeyEvent.CTRL_MASK));

check=new JMenuItem("Check");
check.addActionListener(new MyMenuHandler3());
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,KeyEvent.CTRL_MASK));

submit=new JMenuItem("Submit");
submit.addActionListener(new MyMenuHandler4());
submit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,KeyEvent.CTRL_MASK));

exit=new JMenuItem("Exit");
exit.addActionListener(new MyMenuHandler5());
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,KeyEvent.CTRL_MASK));

game=new JMenu("Game");
game.setMnemonic('g');
game.add(newgame);
game.add(restart);
game.add(new JSeparator());
game.add(check);
game.add(submit);
game.add(new JSeparator());
game.add(exit);

what=new JMenuItem("What is it?");
what.addActionListener(new MyMenuHandler6());
what.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,KeyEvent.CTRL_MASK));

option=new JMenuItem("Options...");
option.addActionListener(new MyMenuHandler7());
option.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,KeyEvent.CTRL_MASK));

myself=new JMenuItem("About me...");
myself.addActionListener(new MyMenuHandler8());
myself.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,KeyEvent.CTRL_MASK));

help=new JMenu("Help");
help.setMnemonic('h');
help.add(what);
help.add(option);
help.add(new JSeparator());
help.add(myself);

menubar=new JMenuBar();
menubar.add(game);
menubar.add(help);

pcenter=new JPanel();
pcenter.setBackground(Color.black);
pcenter.setVisible(false);
pcenter.setLayout(new GridLayout(3,3,5,5));
for(int i=0;i<9;i++)
{
pcenter.add(p[i]);
}

l1.setForeground(Color.white);
l2.setForeground(Color.white);
l3.setForeground(Color.white);
l4.setForeground(Color.white);
l5.setForeground(Color.white);

pnorth=new JPanel();
pnorth.setBackground(Color.black);
pnorth.add(l1);
pnorth.add(l4);
pnorth.add(l2);
pnorth.add(l5);
pnorth.add(l3);
pnorth.setVisible(false);

myframe=new JFrame("Sudoku \t \t \t \t ~~ created by Minal ~~ \t \t \t \t");
myframe.setVisible(true);
myframe.setSize(500,500);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
myframe.setLocation(d.width/5,d.height/5);
myframe.setJMenuBar(menubar);
myframe.setLayout(new BorderLayout());
myframe.add(pcenter,BorderLayout.CENTER);
myframe.add(pnorth,BorderLayout.NORTH);
myframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
myframe.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(JOptionPane.showConfirmDialog(myframe,"Do you want to exit?", "Confirming Exit",JOptionPane.YES_NO_OPTION)==0)
{
System.exit(0);
}
}
});

} // initialize

public void keyPressed(KeyEvent ke)
{
int key=ke.getKeyCode();
int a=row,b=column;

if(key==KeyEvent.VK_RIGHT)
{
b++;
if(b==9) { a++;
if(a==9) { a=0; }
b=0;
}
txt[a][b].requestFocus(true);
column=b;
row=a;
}

if(key==KeyEvent.VK_DOWN)
{
a++;
if(a==9) { a=0; }
txt[a][b].requestFocus(true);
row=a;
}

if(key==KeyEvent.VK_LEFT)
{
b--;
if(b<0) { a--;
if(a<0) { a=8; }
b=8;
}
txt[a][b].requestFocus(true);
column=b;
row=a;
}

if(key==KeyEvent.VK_UP)
{
a--;
if(a<0) { a=8; }
txt[a][b].requestFocus(true);
row=a;
}

} //key

public void keyReleased(KeyEvent ke)
{
int x=Integer.valueOf(ke.getKeyChar());
x=x-48;
if(txt[row][column].isEditable())
{
if(x>=1 && x<=9) { txt[row][column].setText(String.valueOf(x)); }
else if(txt[row][column].getText().length()==1)
{
try { int y=Integer.parseInt(txt[row][column].getText()); }
catch(NumberFormatException e){ txt[row][column].setText(""); }
}
else if(txt[row][column].getText().length()>1) { txt[row][column].setText(txt[row][column].getText().substring(0,txt[row][column].getText().length()-1)); }
}
}

public void keyTyped(KeyEvent ke) {}

public void mouseClicked(MouseEvent me)
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(txt[i][j].isFocusOwner())
{
row=i;
column=j;
}
}
}
}

public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}

public void run()
{
l4.setText(" : ");
l5.setText(" : ");
l1.setText("00");
l2.setText("00");
l3.setText("00");
Repeat mytimer = new Repeat();
timer.schedule(mytimer,1000,1000);
} //run

class Repeat extends TimerTask
{
public void run()
{
int x = Integer.parseInt(l3.getText())+1;
int y = Integer.parseInt(l2.getText());
int z = Integer.parseInt(l1.getText());
if(x==60) { y=y+1; x=0; }
if(z==60) { z=z+1; y=0; }
String a = String.valueOf(x) , b = String.valueOf(y) , c = String.valueOf(z);
if(a.length()==1) { a = "0"+a; }
if(b.length()==1) { b = "0"+b; }
if(c.length()==1) { c = "0"+c; }
l3.setText(a);
l2.setText(b);
l1.setText(c);
}
} //repeat class

class MyMenuHandler1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(myflag)
{
if(JOptionPane.showConfirmDialog(myframe,"Start a new game?","",JOptionPane.YES_NO_OPTION)==0)
{

myframe.setVisible(false);
initialize();
new Difficult();
}
}
else
{
new Difficult();
}
}

class Difficult implements ActionListener
{

JFrame frame1;
JPanel pcenter1;
JLabel label;
JButton ok;
JRadioButton easy,average,difficult,hard;
ButtonGroup bg;

Difficult()
{

label=new JLabel("Choose your difficulty level :");
label.setFont(new Font("Georgia",Font.ITALIC,18));

easy=new JRadioButton(" Beginner ",false);
average=new JRadioButton(" Learner ",false);
hard=new JRadioButton(" Champion ",false);
difficult=new JRadioButton(" Player ",true);

easy.setFont(new Font("Gill Sans MT",Font.BOLD,16));
average.setFont(new Font("Gill Sans MT",Font.BOLD,16));
difficult.setFont(new Font("Gill Sans MT",Font.BOLD,16));
hard.setFont(new Font("Gill Sans MT",Font.BOLD,16));

easy.setBackground(Color.green);
average.setBackground(Color.green);
difficult.setBackground(Color.green);
hard.setBackground(Color.green);

bg=new ButtonGroup();
bg.add(easy);
bg.add(average);
bg.add(difficult);
bg.add(hard);

ok=new JButton("OK");
ok.addActionListener(this);

pcenter1=new JPanel();
pcenter1.setBackground(Color.green);
pcenter1.add(label);
pcenter1.add(easy);
pcenter1.add(new JLabel(" "));
pcenter1.add(new JLabel(" "));
pcenter1.add(average);
pcenter1.add(new JLabel(" "));
pcenter1.add(new JLabel(" "));
pcenter1.add(difficult);
pcenter1.add(new JLabel(" "));
pcenter1.add(new JLabel(" "));
pcenter1.add(hard);
pcenter1.add(new JLabel(" "));
pcenter1.add(new JLabel(" "));
pcenter1.add(ok);

frame1=new JFrame("Levels of Difficulty");
frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(350,350);
frame1.add(pcenter1);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
frame1.setLocation(d.width/3,d.height/3);

} //cons

public void actionPerformed(ActionEvent ae)
{
if(easy.isSelected())
{
mychoice=6;
}
if(average.isSelected())
{
mychoice=5;
}
if(difficult.isSelected())
{
mychoice=4;
}
if(hard.isSelected())
{
mychoice=3;
}
frame1.setVisible(false);
pcenter.setVisible(true);
hide(mychoice);
pnorth.setVisible(true);
l1.setText("00");
l2.setText("00");
l3.setText("00");
} //action
} //difficult
} // handler

class MyMenuHandler2 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(pcenter.isVisible())
{
if(JOptionPane.showConfirmDialog(myframe,"Do you want to restart this game?","",JOptionPane.YES_NO_OPTION)==0)
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(txt[i][j].isEditable())
{
txt[i][j].setText(null);
txt[i][j].setBackground(Color.pink);
} //if
} //for j
} //for i
l1.setText("00");
l2.setText("00");
l3.setText("00");
}
}
}
}

class MyMenuHandler3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
int number=0;
boolean flag=true;
for(int i=0;i<9 && flag;i++)
{
for(int j=0;j<9 && flag;j++)
{
if(txt[i][j].getText().length()==1 && txt[i][j].isEditable())
{
number=Integer.parseInt(txt[i][j].getText());
if(txt[i][j].getBackground()==Color.white)
{
txt[i][j].setBackground(Color.pink);
}
if(number!=arr[i][j])
{
txt[i][j].setBackground(Color.white);
flag=false;
}
}
} // for j
} // for i
} // action
} // handler

class MyMenuHandler4 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

int i,j=0;
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
if(txt[i][j].isEditable())
{
if(txt[i][j].getText().length()<1)
{
if(JOptionPane.showConfirmDialog(myframe,"Sudoku is not Correct...Continue?","",JOptionPane.YES_NO_OPTION)==0)
{
return;
}
else
{

System.exit(0);
}
} //if txt<1
} //if txt editable
} //for j
} //for i
if(i==9 && j==9)
{

callToCheck();
}

} // action

void callToCheck()
{
boolean checkflag=true;
int sum=0;
for(int i=0;i<9 && checkflag;i++)
{
for(int j=0;j<9 && checkflag;j++)
{
sum=sum+Integer.parseInt(txt[i][j].getText());
}
if(sum==45)
{
sum=0;
}
else
{
checkflag=false;
}
}

if(checkflag)
{
int sum1=0;
for(int l=0;l<9 && checkflag;)
{
for(int k=0;k<9 && checkflag;)
{
for(int i=k;i{
for(int j=l;j{
sum1=sum1+Integer.parseInt(txt[i][j].getText());
} //for j
} //for i
if(sum1==45)
{
sum1=0;
}
else
{
checkflag=false;
}
k=k+3;
} //for k
l=l+3;
} //for l
}

if(checkflag)
{
timer1();
pcenter.setVisible(false);
return;
}
else
{
if(JOptionPane.showConfirmDialog(myframe,"Sudoku is not Correct...Continue?","",JOptionPane.YES_NO_OPTION)==0)
{
return;
}
else
{
System.exit(0);
}
}
} //callToCheck
} //handler

class MyMenuHandler5 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(JOptionPane.showConfirmDialog(myframe,"Do you want to exit?", "Confirming Exit",JOptionPane.YES_NO_OPTION)==0)
{

System.exit(0);
}
}
} // handler

class MyMenuHandler6 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new Info1();
} // action
} // handler

class MyMenuHandler7 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new Info2();
} // action
} // handler

class MyMenuHandler8 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new Info3();
} // action
} // handler


void hide(int num)
{
int count=0;
java.util.Random obj=new java.util.Random();
for(int i=0;i<9;i++)
{
for(int j=obj.nextInt(num);j<9;)
{
txt[i][j].setBackground(Color.pink);
txt[i][j].setText(null);
txt[i][j].setEditable(true);

if(count==0)
{
row=i;
column=j;
}
count++;
j=j+obj.nextInt(num);
}
}
myflag=true;
txt[row][column].requestFocus(true);

} // hide

private void timer1()
{
int x = Integer.parseInt(l3.getText());
int y = Integer.parseInt(l2.getText());
int z = Integer.parseInt(l1.getText());
if(z>0) { JOptionPane.showMessageDialog
(myframe,"Congratulations! It's completed but you took very long time.","",JOptionPane.PLAIN_MESSAGE);}
else if(mychoice!=3 && y<10) { JOptionPane.showMessageDialog
(myframe,"Congratulations! It's completed.Try next level.","",JOptionPane.PLAIN_MESSAGE);}
else if(mychoice==3 && y<10) { JOptionPane.showMessageDialog
(myframe,"Congratulations! It's completed.You are a master of Sudoku.","",JOptionPane.PLAIN_MESSAGE);}
else { JOptionPane.showMessageDialog
(myframe,"Congratulations! It's completed.","",JOptionPane.PLAIN_MESSAGE);}
pnorth.setVisible(false);
}

public static void main(String args[])
{
Design objDesign=new Design();
t = new Thread(objDesign);
t.start();
}

} //class

class Info1
{
JFrame f1;
JPanel p1;
JTextArea ta1;
JLabel lb1;

Info1()
{
lb1=new JLabel("Sudoku");
lb1.setForeground(Color.red);
lb1.setFont(new Font("Script MT Bold",Font.BOLD,30));

ta1=new JTextArea("\n\n\n\t The aim of the puzzle is"+
"\n\t to fill each cell of the grid "+
"\n\t with digits from 1 to 9."+
"\n\t Each row , column and "+
"\n\t subgrid must contain only"+
"\n\t one instance of each digit."+
"\n\t Finish the puzzle to win.");
ta1.setFont(new Font("Script MT Bold",Font.PLAIN,22));
ta1.setBackground(Color.yellow);
ta1.setEditable(false);

p1=new JPanel();
p1.setBackground(Color.yellow);
p1.setLayout(new BorderLayout());
p1.add(lb1,BorderLayout.NORTH);
p1.add(ta1,BorderLayout.CENTER);

f1=new JFrame("What is this ?");
f1.setVisible(true);
f1.setSize(450,450);
f1.add(p1);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
f1.setLocation(d.width/4,d.height/4);
} //cons
} // info class

class Info2
{
JFrame f2;
JPanel p2;
JTextArea ta2;
JLabel lb2;

Info2()
{
lb2=new JLabel("You are provided with following options in the menubar :");
lb2.setForeground(Color.red);
lb2.setFont(new Font("Script MT Bold",Font.BOLD,22));

ta2=new JTextArea("\n\n\n New Game : To start a new sudoku. It will close the current puzzle."+
"\n Restart this game : To restart the current game. It will undo your puzzle."+
"\n Check : Shows the cell whose value is incorrect. Only 1 cell is shown once."+
"\n Submit : After finishing, submit your puzzle. Asks if it is incorrect."+
"\n Exit : To exit sudoku.");
ta2.setFont(new Font("Script MT Bold",Font.PLAIN,22));
ta2.setBackground(Color.yellow);
ta2.setEditable(false);

p2=new JPanel();
p2.setBackground(Color.yellow);
p2.setLayout(new BorderLayout());
p2.add(lb2,BorderLayout.NORTH);
p2.add(ta2,BorderLayout.CENTER);

f2=new JFrame("What is this ?");
f2.setVisible(true);
f2.setSize(660,450);
f2.add(p2);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
f2.setLocation(d.width/4,d.height/4);
} //cons
} // info class

class Info3
{
Label three;
JTextArea ta3,me;
JTextField tf3;
JPanel p3;
JFrame f3;

Info3()
{
three=new Label(" \t Developed by :");
three.setForeground(Color.red);
three.setAlignment(Label.LEFT);
three.setFont(new Font("Lucida Sans Typewriter",Font.BOLD,16));

me=new JTextArea("Er. Minal Bansal ");
me.setEditable(false);
me.setBackground(Color.orange);
me.setFont(new Font("Pristina",Font.BOLD,30));
me.setForeground(Color.blue);

ta3=new JTextArea("\n \t Hey friends ! "+
"\n\t Hope you like my creation."+
"\n\t Enjoy !"+
"\n\t You can send me email on \t");
ta3.setEditable(false);
ta3.setBackground(Color.orange);
ta3.setFont(new Font("Papyrus",Font.BOLD,18));

tf3=new JTextField("minalbansal.hr@gmail.com");
tf3.setEditable(false);
tf3.setBackground(Color.orange);
tf3.setForeground(Color.red);
tf3.setFont(new Font("Rage Italic",Font.PLAIN,26));

p3=new JPanel();
p3.setBackground(Color.orange);
p3.add(three);
p3.add(me);
p3.add(ta3);
p3.add(tf3);

f3=new JFrame("About the developer...");
f3.setVisible(true);
f3.setSize(500,400);
f3.add(p3);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
f3.setLocation(d.width/4,d.height/4);

} //cons
} //class

Download

Puzzle

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

public class Puzzle extends JFrame implements KeyListener
{
static int[][] a={{11,0,7,3},{15,6,9,8},{2,10,13,1},{4,12,5,14}};
int i,j, row=3,col=3;
JTextField[][] tf=new JTextField[4][4];


Puzzle()
{
setTitle("puzzle");
setLayout(new GridLayout(4,4));


for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
tf[i][j]=new JTextField("");
tf[i][j].setText(""+a[i][j]);
tf[i][j].setHorizontalAlignment(JTextField.CENTER);
tf[i][j].setFont(new Font("Georgia",Font.BOLD,26));
tf[i][j].setBackground(Color.black);
tf[i][j].setForeground(Color.white);

tf[i][j].setEditable(false);
add(tf[i][j]);
tf[i][j].addKeyListener(this);
if(Integer.parseInt(tf[i][j].getText())==0)
{
tf[i][j].setEditable(true);
tf[i][j].setText("");
row=i;col=j;
}
}
}

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(200,250);
setLocation(300,300);
}


public void keyPressed(KeyEvent ke)
{

int key=ke.getKeyCode();

if(key==KeyEvent.VK_UP)
{
if(row==0)
{
}
else
{
String temp=tf[row-1][col].getText();
tf[row-1][col].setText("");
tf[row-1][col].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
row=row-1;
}
check();
}

if(key==KeyEvent.VK_DOWN)
{
if(row==3)
{
}
else
{
String temp=tf[row+1][col].getText();
tf[row+1][col].setText("");
tf[row+1][col].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
row=row+1;
}
check();
}



if(key==KeyEvent.VK_LEFT)
{
if(col==0)
{
}
else
{
String temp=tf[row][col-1].getText();
tf[row][col-1].setText("");
tf[row][col-1].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
col=col-1;
}
check();
}


if(key==KeyEvent.VK_RIGHT)
{
if(col==3)
{
}
else
{
String temp=tf[row][col+1].getText();
tf[row][col+1].setText("");
tf[row][col+1].setEditable(true);
tf[row][col].setText(temp);
tf[row][col].setEditable(false);
col=col+1;
}
check();
}

}

public void check()
{
try
{
int n=1;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
int m=Integer.parseInt(tf[i][j].getText());
if(m==n)
{
if(n==15)
{
JOptionPane.showMessageDialog(this," Congratulations ! Puzzle is done. You won.","Message",JOptionPane.PLAIN_MESSAGE);
int choice=JOptionPane.showConfirmDialog(this,"Do you want to restart ?","Question Message",JOptionPane.YES_NO_OPTION);
if(choice==0)
{
setVisible(false);
new Puzzle().setVisible(true);
}
else
{
setVisible(false);
}
}
n++;
}
}
}
}
catch(Exception e)
{}
}

public void keyReleased(KeyEvent ke)
{}

public void keyTyped(KeyEvent ke)
{}

public static void main(String args[])
{
new Puzzle();
}
}
Download

Point to Point Chat Server

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.*;
import java.sql.*;
class Client extends JFrame implements ActionListener
{
String name;
String msg;
String target="";
int index;
Socket s;
InputStreamReader isr;
BufferedReader br;
PrintWriter pw;

/*login frame data*/
JFrame loginframe;
JButton login,cancel1;
JTextField loginid;
JLabel loginlb;
Icon canimg,logimg;

/*chat frame data*/
JFrame chatframe;
JTextArea text;
JTextField datatosend;
JButton send;
JButton clear;
JScrollPane jp,jp1;
JLabel received,wannasend;
JComboBox cb;
JButton logout;
JButton sendtoall;
Icon sendicon,logouticon,clearicon,sendtoallicon;
Client()
{
try
{
s=new Socket("localhost",8080);
isr=new InputStreamReader(s.getInputStream());
br=new BufferedReader(isr);
pw=new PrintWriter(s.getOutputStream());
Readdata m=new Readdata(isr);
Thread t1=new Thread(m);
t1.start();
}
catch(Exception e){
System.out.println(""+e);
}



/*chat frame begin*/
chatframe=new JFrame();
text=new JTextArea();
datatosend=new JTextField();
text.setEditable(false);

sendicon=new ImageIcon("send.png");
logouticon=new ImageIcon("logout.png");
clearicon=new ImageIcon("clear.png");
sendtoallicon=new ImageIcon("sendtoall.gif");

send=new JButton(sendicon);
clear=new JButton(clearicon);
logout=new JButton(logouticon);
sendtoall=new JButton(sendtoallicon);


jp=new JScrollPane(text);
jp1=new JScrollPane(datatosend);

received=new JLabel("Received msg:");
wannasend=new JLabel("Msg to send:");

received.setBounds(10,5,90,30);
jp.setBounds(10,30,250,100);
wannasend.setBounds(10,130,90,30);
jp1.setBounds(10,160,250,80);

send.setBounds(15,250,72,28);
clear.setBounds(120,250,72,28);
logout.setBounds(250,250,72,28);
sendtoall.setBounds(370,250,80,28);

chatframe.setLayout(null);
chatframe.add(received);
chatframe.add(jp);
chatframe.add(wannasend);
chatframe.add(jp1);
chatframe.add(send);
chatframe.add(clear);
chatframe.add(sendtoall);

//chatframe.setVisible(true);
chatframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
chatframe.addWindowListener(new appCloseHandler());
cb=new JComboBox();
cb.setBounds(280,30,170,30);
chatframe.add(cb);
cb.addActionListener(new comboboxhandler());

chatframe.add(logout);
chatframe.setSize(500,350);


clear.addActionListener(this);
logout.addActionListener(this);
send.addActionListener(this);
sendtoall.addActionListener(this);

/*chatframe ends*/

/*login frame begin*/
loginframe=new JFrame("login@milan.com");

loginframe.setLocation(400,300);
loginid=new JTextField();
loginlb=new JLabel("Login-Id:");
canimg=new ImageIcon("cancel.png");
logimg=new ImageIcon("login.png");

login=new JButton(logimg);
cancel1=new JButton(canimg);


loginframe.setLayout(null);
loginframe.setVisible(true);
loginframe.setSize(230,150);
loginlb.setBounds(10,5,80,30);
loginid.setBounds(80,10,130,20);


login.setBounds(15,50,72,28);
cancel1.setBounds(130,50,72,28);

loginframe.add(login);
loginframe.add(loginid);
loginframe.add(loginlb);
loginframe.add(cancel1);

login.addActionListener(this);
cancel1.addActionListener(this);

loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*loginframe ends*/
}
public String getname()
{
return(name);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
datatosend.setText("");
}
if(e.getSource()==cancel1)
{
loginid.setText("");
//System.exit(0);
}
if(e.getSource()==login)
{
name=loginid.getText();
chatframe.setTitle(name);
loginframe.setVisible(false);
chatframe.setVisible(true);
String st=name+"123logged";

try{
pw.flush();
pw.println(st);
pw.flush();
}
catch(Exception e1){System.out.println("exception1:"+e1);}
}

if(e.getSource()==send)
{
String str="::"+name+"::"+target+"::"+datatosend.getText()+"::"+index;
datatosend.setText("");
try
{
pw.flush();
pw.println(str);
pw.flush();
}
catch(Exception ew)
{
System.out.println("send error");
}
}

if(e.getSource()==sendtoall)
{
String str="@"+name+"@"+datatosend.getText();
datatosend.setText("");
try
{
pw.flush();
pw.println(str);
pw.flush();
}
catch(Exception ew)
{
System.out.println("send error");
}
}

if(e.getSource()==logout)
{
logout();
}

}


public void logout()
{
System.out.println("index is "+getNameIndex(name));
String str="~"+name+"~"+"logout";
try
{
pw.flush();
pw.println(str);
pw.flush();
}
catch(Exception e5)
{
System.out.println("logout errot");
}
System.exit(0);
}


public int getNameIndex(String name)
{
int index=0;
for(int j=0;j{
String temp=(String)cb.getItemAt(j);
if(temp.equals(name))
index=j;
}
return index;
}


public static void main(String... s)
{
new Client();
}


class Readdata implements Runnable
{
InputStreamReader isr;
BufferedReader br;
Readdata(InputStreamReader isr)
{
this.isr=isr;
br=new BufferedReader(isr);
}
public void run()
{

String s1="";
do
{
try
{

s1=br.readLine();
if(s1.startsWith("*"))
{
System.out.println("data recieved"+s1);
String[] clientname=s1.split("123");
cb.addItem(clientname[1]);
}

else if(s1.startsWith("#"))
{
String[] temp=s1.split("#");
//System.out.println("length is "+temp.length);
for(int i=0;i System.out.println("data is "+temp[i]);
int removeindex=Integer.parseInt(""+getNameIndex(temp[2]));
cb.removeItemAt(removeindex);
}


else{
text.append(s1+"\n");
text.setCaretPosition(text.getText().length());
}
}
catch(Exception e)
{
System.out.println("exception2:"+e);
}
}while(s1!=null);

}
}


/*class sendListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{

}
}*/


class comboboxhandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
target=(String)cb.getSelectedItem();
index=(int)cb.getSelectedIndex();
}
}



class appCloseHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
logout();
}
}

}//class end

//Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
ArrayList al;
ArrayList namelist;
ServerSocket ss;
Socket s;
String name;
String cl="*";
String source="";
String target="";
String datatosend="";
int index;
Server()
{
try
{
al=new ArrayList();
namelist=new ArrayList();
ss=new ServerSocket(8080);
System.out.println("Server Started");
while(true)
{
s=ss.accept();
al.add(s);
Runnable r=new serverread(s,al);
Thread t=new Thread(r);
t.start();
}

}
catch(Exception exc)
{
System.out.println("exception:"+exc);
}
}//constructor ends

public static void main(String... s)
{
new Server();
}

class serverread implements Runnable
{
Socket s;
ArrayList me;
serverread(Socket s,ArrayList me)
{
this.s=s;
this.me=me;
}

public void run()
{
String data="";
try
{
InputStreamReader isr=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
do{
data=new String(br.readLine());
if(data.startsWith("::"))
{
System.out.println("data to send is "+data);
String token[]=data.split("::");
source=token[1];
target=token[2];
datatosend=token[3];
index=Integer.parseInt(""+getNameIndex(target));
sendtotarget(source,target,datatosend,index);
}
else if(data.endsWith("logged"))
{
String[] tokens=data.split("123");
name=tokens[0];
namelist.add(name);
updateotherclient(name);
}

else if(data.startsWith("@"))
{
System.out.println("data starts with @");
String tok[]=data.split("@");
for(int i=0;i System.out.println("token is:"+tok[i]);
source=tok[1];
datatosend=tok[2];
int index=getNameIndex(source);
sendexceptme(index,datatosend,source);
}


else
{
System.out.println("ends with logout");
System.out.println(data);
String[] temp=data.split("~");
for(int j=0;j System.out.println("logout data is "+temp[j]);
String removeclientname=temp[1];
int removeindex=getNameIndex(removeclientname);
al.remove(removeindex);
namelist.remove(removeindex);
updateeveryclient("#"+"x"+"#"+removeclientname+"#");
}


}while(data!=null);
}
catch(Exception es)
{
System.out.println("exception:"+es);
}
}

public int getNameIndex(String name)
{
int index=0;
for(int j=0;j{
String temp=namelist.get(j);
if(temp.equals(name))
index=j;
}
return index;
}


public void updateotherclient(String name)
{
try
{
for(int i=0;i{
Socket sc=al.get(i);
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.flush();
pw.println("*"+"123"+name+"123"+"*");
pw.flush();
}
for(int j=0;j{
Socket sc=al.get(namelist.size()-1);
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.flush();
pw.println("*"+"123"+namelist.get(j)+"123"+"*");
pw.flush();
}
}
catch(Exception er)
{
System.out.println("error:"+er);
}
}

public void sendtotarget(String source,String target,String datatosend,int index)throws Exception
{
String lastdata=source+":"+datatosend;
Socket sc=al.get(index);
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.flush();
pw.println(lastdata);
pw.flush();
}

public void sendexceptme(int index,String datatosend,String src)
{
String data=src+":"+datatosend;
try
{
for(int i=0;i{
if(i!=index)
{
Socket sc=al.get(i);
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.flush();
pw.println(data);
pw.flush();
}
}
}
catch(Exception er)
{
System.out.println("error:"+er);
}
}

public void updateeveryclient(String cl)throws Exception
{
try
{
for(int i=0;i{
Socket sc=al.get(i);
PrintWriter pw=new PrintWriter(sc.getOutputStream());
pw.flush();
pw.println(cl);
pw.flush();
}
}
catch(Exception er)
{
System.out.println("error:"+er);
}
}
}
}

//Please use different names to login.........

Download

MyJavap Tool

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

class Myjavap implements ActionListener
{
JFrame mainFrame;
JPanel upperPanel;
JPanel lowerPanel;
JTextField textField;
JTextArea textArea;
JScrollPane sp;
JLabel intro;
int flag=0;
String mod="";
String fields="";
String superclass="";
String interfaces="";
String constructors="";
String methods="";
String finalinf="";
Myjavap()
{
mainFrame=new JFrame("MyjavapTool ~~~~~Milan~~~~~");
upperPanel=new JPanel();
textField=new JTextField("java.awt.Color");
intro=new JLabel("Enter the class name to find its content(press enter):",JLabel.CENTER);


upperPanel.setLayout(new GridLayout(2,1));
textField.requestFocus();
textField.setFont(new Font("Comic Sams MS",Font.PLAIN,15));
upperPanel.add(intro);
upperPanel.add(textField);

lowerPanel=new JPanel(new BorderLayout());
textArea=new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setFont(new Font("Comic Sams MS",Font.PLAIN,15));
sp=new JScrollPane(textArea);
lowerPanel.add(sp);

mainFrame.add(upperPanel,BorderLayout.NORTH);
mainFrame.add(lowerPanel,BorderLayout.CENTER);

mainFrame.setSize(700,600);
mainFrame.setVisible(true);
mainFrame.setLocation(150,75);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

textField.addActionListener(this);
}

public static void main(String... s)
{
new Myjavap();
}

public void actionPerformed(ActionEvent e)
{
flag=0;
try
{
Class c=Class.forName(textField.getText());
textArea.setText(getClassInformation(c));
textArea.setCaretPosition(0);
}
catch(Exception p)
{
System.out.println("ok error"+p);
JOptionPane.showMessageDialog(null,"Entered class Doesn't exist..", "Error",JOptionPane.ERROR_MESSAGE);
}
}

public String getClassInformation(Class c)
{
mod=getClassModifiers(c);
if(flag==0)
{
superclass=getClassSuperClass(c);
}
interfaces=getClassInterfaces(c,flag);
fields=getClassFields(c);
if(flag==0)
{
constructors=getClassConstructors(c);
}
methods=getClassMethods(c);
if(flag==0)
finalinf=mod+" "+superclass+interfaces+"\n"+"{"+"\n"+fields+constructors+methods+"}";
else
finalinf=mod+" "+c.getName()+" "+interfaces+"\n"+"{"+"\n"+fields+methods+"}";
return finalinf;
}

public String getClassModifiers(Class temp)
{
int m=temp.getModifiers();
if(Modifier.isInterface(m))
{
flag++;
}
return (Modifier.toString(m));
}

public String getClassSuperClass(Class c)
{
Class tmp=c.getSuperclass();
String str="";
str="class "+c.getName()+" extends "+tmp.getName();
return str;
}


public String getClassInterfaces(Class c,int flag)
{
String str="";
String temp="";
Class inter[]=c.getInterfaces();
for(int i=0;i{
temp=temp+" "+inter[i].getName()+",";
}
if(flag==0 && inter.length>0)
{
str=str+" implements"+temp;
}
else
{
if(inter.length>0)
str=str+" extends"+temp;
}
return str;
}

public String getClassFields(Class c)
{
String tmp="";
Field f[]=c.getDeclaredFields();
for(int i=0;i{
Class type=f[i].getType();
int m=f[i].getModifiers();
tmp+=Modifier.toString(m)+" "+type.getName()+" "+f[i].getName()+";"+"\n";
}
return tmp;
}


public String getClassConstructors(Class c)
{
Constructor cs[]=c.getDeclaredConstructors();
String temp="";
String temp1="";
for(int i=0;i{
int m=cs[i].getModifiers();
temp=temp+Modifier.toString(m)+" "+cs[i].getName()+"(";
Class type[]=cs[i].getParameterTypes();
temp1="";
for(int k=0;k{
temp1=temp1+type[k].getName()+",";
}
temp=temp+temp1+")"+";"+"\n";
}
return temp;
}


public String getClassMethods(Class c)
{
Method m[]=c.getDeclaredMethods();
String temp="";
String temp1="";
String temp2="";
String st="throws";
for(int i=0;i{
int r=m[i].getModifiers();
temp=temp+Modifier.toString(r)+" "+m[i].getReturnType().getName()+" "+m[i].getName()+"(";
Class type[]=m[i].getParameterTypes();
temp1="";
for(int k=0;k{
temp1=temp1+type[k].getName()+",";
}
temp=temp+temp1+")"+";"+"\n";
}

return temp;
}
}//end class

Download

ExplorerPlus

ExplorerPlus
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import java.net.*;

class MyExplorer implements TreeSelectionListener
{
ImageIcon def=new ImageIcon(".\\java.jpg");

static JFrame frame;
JLabel label;
JTextField textField;
JPanel upperPanel,lowerPanel,showPanel;
JTable table;
File f;
JTree tree;
JScrollPane sp,sp1;
JEditorPane editorPane;
JScrollPane sp2;
JPanel imagePanel;
JLabel imageLabel;
JPanel mainPanel;
MyExplorer()
{
frame=new JFrame("MyExplorer: ~~~~~~By:Milan~~~~~~");
label=new JLabel("Enter A Valid Directory Path and Press Enter:",JLabel.CENTER);
textField = new JTextField();
textField.addActionListener(new TextFieldListener());

String home = System.getProperty("user.home");
textField.setText(home);


upperPanel = new JPanel(new GridLayout(2,1));
upperPanel.add(label);
upperPanel.add(textField);

lowerPanel=new JPanel(new GridLayout(1,2));
table=new JTable(new DirectoryModel(new File(home)));
f=new File(home);
tree=new JTree(createNodes(null,f));
tree.addTreeSelectionListener(this);
sp=new JScrollPane(tree);
lowerPanel.add(sp,0,0);
sp1=new JScrollPane(table);
lowerPanel.add(sp1,0,1);


showPanel=new JPanel();
showPanel.setLayout(new GridLayout(1,2));
editorPane=new JEditorPane();
//editorPane.setText("ok");
editorPane.setEditable(false);
sp2=new JScrollPane(editorPane);
imagePanel=new JPanel();
imageLabel=new JLabel("",JLabel.CENTER);
imageLabel.setIcon(new ImageIcon(def.getImage().getScaledInstance(500,300,Image.SCALE_DEFAULT)));
imagePanel.setLayout(new BorderLayout());
imagePanel.add(new JScrollPane(imageLabel));
showPanel.add(imagePanel);
showPanel.add(sp2);

mainPanel=new JPanel();
mainPanel.setLayout(new GridLayout(2,2));

//frame.setLayout(new GridLayout(0,1));

mainPanel.add(lowerPanel);
mainPanel.add(showPanel);

frame.add(upperPanel,BorderLayout.NORTH);
frame.add(mainPanel);


//frame.pack();
Toolkit t=Toolkit.getDefaultToolkit();
int height=t.getScreenSize().height;
int width=t.getScreenSize().width;
frame.setSize(width,height-50);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String... s)
{
new MyExplorer();
Date d = new Date();
JPanel datePanel = new JPanel();
JLabel label = new JLabel(d.toLocaleString());
datePanel.add(label);
frame.add(datePanel,"South");
while(true)
{
d=new Date();
label.setText(""+d.toLocaleString());
}

}

class TextFieldListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
File temp=new File(textField.getText());
if(temp.exists())
{
setTree();
setTable();
}
else
JOptionPane.showMessageDialog(null,"file/directory does not exits","Error",JOptionPane.ERROR_MESSAGE);
}
}

public void setTree()
{
f=new File(textField.getText());
tree=new JTree(createNodes(null,f));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
lowerPanel.removeAll();
sp=new JScrollPane(tree);
lowerPanel.add(sp,0,0);
tree.addTreeSelectionListener(this);
}

public void setTable()
{
lowerPanel.remove(sp1);
sp1=new JScrollPane(new JTable(new DirectoryModel(new File(textField.getText()))));
lowerPanel.add(sp1,0,1);
lowerPanel.updateUI();
}


public void setFileTable()
{
lowerPanel.remove(sp1);
sp1=new JScrollPane(new JTable(new FileModel(new File(textField.getText()))));
lowerPanel.add(sp1,0,1);
lowerPanel.updateUI();
}



DefaultMutableTreeNode createNodes(DefaultMutableTreeNode top, File dir)
{
String curPath = dir.getPath();
Vector files = new Vector();
File f;
//File tmpf=new File(curPath);
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (top != null)
{
top.add(curDir);
}
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
{
String path=tmp[i];
String newpath;
if (curPath.equals("."))
newpath = path;
else
newpath = curPath + File.separator + tmp[i];

if ((f = new File(newpath)).isDirectory())
createNodes(curDir, f);
else
files.addElement(curPath+File.separator+path);
}
for (int j = 0; j {
curDir.add(new DefaultMutableTreeNode(files.elementAt(j)));
}
return curDir;
}

public void valueChanged(TreeSelectionEvent e)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(node==null)
{
System.out.println("node is null");
return;
}
Object nodeInfo = node.getUserObject();
File f=new File(nodeInfo.toString());
if(f.isDirectory())
{
textField.setText(f.getPath());
setTable();
editorPane.setText("This is a Directory not a File");
imageLabel.setIcon(new ImageIcon(def.getImage().getScaledInstance(500,300,Image.SCALE_DEFAULT)));
}
else
{
textField.setText(nodeInfo.toString());
setFileTable();
setEditorPane(nodeInfo.toString());
}
}

public void setEditorPane(String path)
{
File file=new File(path);
String filename=file.getName();
if(filename.endsWith(".txt")||filename.endsWith(".java")||filename.endsWith(".c")||filename.endsWith(".cpp")||filename.endsWith(".css"))
{
openFile(file);
}
else if(filename.endsWith(".jpg")||filename.endsWith(".JPG")||filename.endsWith(".JPEG") || filename.endsWith(".jpeg")||
filename.endsWith(".gif")||filename.endsWith(".GIF") || filename.endsWith(".png")||filename.endsWith(".PNG")||
filename.endsWith(".bmp")||filename.endsWith(".BMP"))
{
ImageIcon temp=new ImageIcon(file.getPath());
ImageIcon thumbnail=temp;
if (temp.getIconWidth() >380 || temp.getIconHeight()>300)
{
thumbnail = new ImageIcon(temp.getImage().getScaledInstance(500,300,Image.SCALE_DEFAULT));
}
imageLabel.setText("");
imageLabel.setIcon(thumbnail);
}
else
{
imageLabel.setIcon(new ImageIcon("java.jpeg"));
editorPane.setText("this is not a txt,java,c,cpp,css file");
//imageLabel.setText("not an image");
//ImageIcon t=new ImageIcon("java.jpg");
def=new ImageIcon(def.getImage().getScaledInstance(500,300,Image.SCALE_DEFAULT));
imageLabel.setIcon(def);
imageLabel.repaint();
}
}

public void openFile(File file)
{
String data="";
String temp="";
try
{
BufferedReader br=new BufferedReader(new FileReader(file));
while((data=br.readLine())!=null)
{
data=data+"\n";
temp=temp+data;
}
//System.out.println(data);
editorPane.setText(temp);
editorPane.setCaretPosition(0);
showPanel.updateUI();
}
catch(Exception e)
{
System.out.println("exception on reading file");
}
}


}//end class Explorer


class DirectoryModel extends AbstractTableModel
{
File directory;
String[] members;
int rowCount;

public DirectoryModel(File dir)
{
directory = dir; // Hold the directory
members = dir.list(); // Get the list of files and subdirectories
if (members != null)

// Table rows = No. of entities inside the directory
rowCount = members.length;

else
{
// If the memeber list is null, row count should be zero.
rowCount = 0;
// This can happen if an invalid directory is entered in the text field.
System.out.println("Not a valid directory!");
}
}

//get the number of rows for the table to be prepared.
public int getRowCount()
{
return (members != null? rowCount:0);
}

//get the column count.
public int getColumnCount()
{
return members != null? 6:0;
}

// get each of the table values at the specified row and column.
public Object getValueAt(int row, int column)
{
if (directory == null || members == null)
{
return null;
}

File fileSysEntity = new File(directory, members[row]);
switch(column)
{
case 0: //name
return fileSysEntity.getName();
case 1: //size
if (fileSysEntity.isDirectory())
{
return "...";
}
else
{
return new Long(fileSysEntity.length());
}
case 2:
if(fileSysEntity.canRead())
{
return (new Boolean("true"));
}
else
{
return (new Boolean(false));
}

case 3:
if(fileSysEntity.canRead())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}

case 4:
if(fileSysEntity.isHidden())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}


case 5: //directory or not
return fileSysEntity.isDirectory()? new Boolean(true):new Boolean(false);
default:
return "";
}
}

//get the column names to be used in the table header.
public String getColumnName(int column)
{
switch(column)
{
case 0:
return "Name";
case 1:
return "Size";
case 2:
return "Read";
case 3:
return "Write";
case 4:
return "Hidden";
case 5:
return "Directory";
default:
return "";
}
}

//get the class types of the entries in each of the table columns.
public Class getColumnClass(int column)
{
Class returnClass = Boolean.class;
if (column == 0|| column==1)
returnClass = String.class;
return returnClass;
}
}//end class Directory model





class FileModel extends AbstractTableModel
{
File directory;
int rowCount;

public FileModel(File dir)
{
directory = dir; // Hold the directory
rowCount=1;
}

//get the number of rows for the table to be prepared.
public int getRowCount()
{
return 1;
}

//get the column count.
public int getColumnCount()
{
return 5;
}

//get each of the table values at the specified row and column.
public Object getValueAt(int row, int column)
{
if (directory == null)
{
return null;
}

File fileSysEntity = new File(directory.getPath());
switch(column)
{
case 0: //name
return fileSysEntity.getName();

case 1: //size
return new Long(fileSysEntity.length());

case 2:
if(fileSysEntity.canRead())
{
return (new Boolean("true"));
}
else
{
return (new Boolean(false));
}

case 3:
if(fileSysEntity.canRead())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}

case 4:
if(fileSysEntity.isHidden())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}
default:
return "";
}
}

// get the column names to be used in the table header.
public String getColumnName(int column)
{
switch(column)
{
case 0:
return "Name";
case 1:
return "Size";
case 2:
return "Read";
case 3:
return "Write";
case 4:
return "Hidden";
default:
return "";
}
}

//get the class types of the entries in each of the table columns.
public Class getColumnClass(int column)
{
Class returnClass = Boolean.class;
if (column == 0 || column==1)
returnClass = String.class;
return returnClass;
}
}//end class Filemodel

Download

Explorer

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
import java.net.*;

class MyExplorer implements TreeSelectionListener
{
static JFrame frame;
JLabel label;
JTextField textField;
JPanel upperPanel,lowerPanel,showPanel;
JTable table;
File f;
JTree tree;
JScrollPane sp,sp1;
JEditorPane editorPane;
JScrollPane sp2;
JPanel imagePanel;
JLabel imageLabel;
JPanel mainPanel;
MyExplorer()
{
frame=new JFrame("MyExplorer: ~~~~~~By:Milan~~~~~~");
label=new JLabel("Enter A Valid Directory Path and Press Enter:",JLabel.CENTER);
textField = new JTextField();
textField.addActionListener(new TextFieldListener());

String home = System.getProperty("user.home");
textField.setText(home);


upperPanel = new JPanel(new GridLayout(2,1));
upperPanel.add(label);
upperPanel.add(textField);

lowerPanel=new JPanel(new GridLayout(1,2));
table=new JTable(new DirectoryModel(new File(home)));
f=new File(home);
tree=new JTree(createNodes(null,f));
tree.addTreeSelectionListener(this);
sp=new JScrollPane(tree);
lowerPanel.add(sp,0,0);
sp1=new JScrollPane(table);
lowerPanel.add(sp1,0,1);


showPanel=new JPanel();
showPanel.setLayout(new GridLayout(1,2));
editorPane=new JEditorPane();
//editorPane.setText("ok");
editorPane.setEditable(false);
sp2=new JScrollPane(editorPane);
imagePanel=new JPanel();
imageLabel=new JLabel("",JLabel.CENTER);
imagePanel.setLayout(new BorderLayout());
imagePanel.add(new JScrollPane(imageLabel));
showPanel.add(imagePanel);
showPanel.add(sp2);

mainPanel=new JPanel();
mainPanel.setLayout(new GridLayout(2,2));

//frame.setLayout(new GridLayout(0,1));

mainPanel.add(lowerPanel);
mainPanel.add(showPanel);

frame.add(upperPanel,BorderLayout.NORTH);
frame.add(mainPanel);


//frame.pack();
Toolkit t=Toolkit.getDefaultToolkit();
int height=t.getScreenSize().height;
int width=t.getScreenSize().width;
frame.setSize(width,height-50);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String... s)
{
new MyExplorer();
Date d = new Date();
JPanel datePanel = new JPanel();
JLabel label = new JLabel(d.toLocaleString());
datePanel.add(label);
frame.add(datePanel,"South");
while(true)
{
d=new Date();
label.setText(""+d.toLocaleString());
}

}

class TextFieldListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
File temp=new File(textField.getText());
if(temp.exists())
{
setTree();
setTable();
}
else
JOptionPane.showMessageDialog(null,"file/directory does not exits","Error",JOptionPane.ERROR_MESSAGE);
}
}

public void setTree()
{
f=new File(textField.getText());
tree=new JTree(createNodes(null,f));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
lowerPanel.removeAll();
sp=new JScrollPane(tree);
lowerPanel.add(sp,0,0);
tree.addTreeSelectionListener(this);
}

public void setTable()
{
lowerPanel.remove(sp1);
sp1=new JScrollPane(new JTable(new DirectoryModel(new File(textField.getText()))));
lowerPanel.add(sp1,0,1);
lowerPanel.updateUI();
}


public void setFileTable()
{
lowerPanel.remove(sp1);
sp1=new JScrollPane(new JTable(new FileModel(new File(textField.getText()))));
lowerPanel.add(sp1,0,1);
lowerPanel.updateUI();
}



DefaultMutableTreeNode createNodes(DefaultMutableTreeNode top, File dir)
{
String curPath = dir.getPath();
Vector files = new Vector();
File f;
//File tmpf=new File(curPath);
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (top != null)
{
top.add(curDir);
}
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
{
String path=tmp[i];
String newpath;
if (curPath.equals("."))
newpath = path;
else
newpath = curPath + File.separator + tmp[i];

if ((f = new File(newpath)).isDirectory())
createNodes(curDir, f);
else
files.addElement(curPath+File.separator+path);
}
for (int j = 0; j {
curDir.add(new DefaultMutableTreeNode(files.elementAt(j)));
}
return curDir;
}

public void valueChanged(TreeSelectionEvent e)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(node==null)
{
System.out.println("node is null");
return;
}
Object nodeInfo = node.getUserObject();
File f=new File(nodeInfo.toString());
if(f.isDirectory())
{
textField.setText(f.getPath());
setTable();
editorPane.setText("This is a Directory not a File");
}
else
{
textField.setText(nodeInfo.toString());
setFileTable();
setEditorPane(nodeInfo.toString());
}
}

public void setEditorPane(String path)
{
File file=new File(path);
String filename=file.getName();
if(filename.endsWith(".txt")||filename.endsWith(".java")||filename.endsWith(".c")||filename.endsWith(".cpp")||filename.endsWith(".css"))
{
openFile(file);
}
else if(filename.endsWith(".jpg")||filename.endsWith(".JPG")||filename.endsWith(".JPEG") || filename.endsWith(".jpeg")||
filename.endsWith(".gif")||filename.endsWith(".GIF") || filename.endsWith(".png")||filename.endsWith(".PNG")||
filename.endsWith(".bmp")||filename.endsWith(".BMP"))
{
ImageIcon temp=new ImageIcon(file.getPath());
ImageIcon thumbnail=temp;
if (temp.getIconWidth() >380 || temp.getIconHeight()>300)
{
thumbnail = new ImageIcon(temp.getImage().getScaledInstance(500,300,Image.SCALE_DEFAULT));
}
imageLabel.setText("");
imageLabel.setIcon(thumbnail);
}
else
{
editorPane.setText("this is not a txt,java,c,cpp,css file");
imageLabel.setText("not an image");
}
}

public void openFile(File file)
{
String data="";
String temp="";
try
{
BufferedReader br=new BufferedReader(new FileReader(file));
while((data=br.readLine())!=null)
{
data=data+"\n";
temp=temp+data;
}
//System.out.println(data);
editorPane.setText(temp);
editorPane.setCaretPosition(0);
showPanel.updateUI();
}
catch(Exception e)
{
System.out.println("exception on reading file");
}
}


}//end class Explorer


class DirectoryModel extends AbstractTableModel
{
File directory;
String[] members;
int rowCount;

public DirectoryModel(File dir)
{
directory = dir; // Hold the directory
members = dir.list(); // Get the list of files and subdirectories
if (members != null)

// Table rows = No. of entities inside the directory
rowCount = members.length;

else
{
// If the memeber list is null, row count should be zero.
rowCount = 0;
// This can happen if an invalid directory is entered in the text field.
System.out.println("Not a valid directory!");
}
}

//get the number of rows for the table to be prepared.
public int getRowCount()
{
return (members != null? rowCount:0);
}

//get the column count.
public int getColumnCount()
{
return members != null? 6:0;
}

// get each of the table values at the specified row and column.
public Object getValueAt(int row, int column)
{
if (directory == null || members == null)
{
return null;
}

File fileSysEntity = new File(directory, members[row]);
switch(column)
{
case 0: //name
return fileSysEntity.getName();
case 1: //size
if (fileSysEntity.isDirectory())
{
return "...";
}
else
{
return new Long(fileSysEntity.length());
}
case 2:
if(fileSysEntity.canRead())
{
return (new Boolean("true"));
}
else
{
return (new Boolean(false));
}

case 3:
if(fileSysEntity.canRead())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}

case 4:
if(fileSysEntity.isHidden())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}


case 5: //directory or not
return fileSysEntity.isDirectory()? new Boolean(true):new Boolean(false);
default:
return "";
}
}

//get the column names to be used in the table header.
public String getColumnName(int column)
{
switch(column)
{
case 0:
return "Name";
case 1:
return "Size";
case 2:
return "Read";
case 3:
return "Write";
case 4:
return "Hidden";
case 5:
return "Directory";
default:
return "";
}
}

//get the class types of the entries in each of the table columns.
public Class getColumnClass(int column)
{
Class returnClass = Boolean.class;
if (column == 0|| column==1)
returnClass = String.class;
return returnClass;
}
}//end class Directory model





class FileModel extends AbstractTableModel
{
File directory;
int rowCount;

public FileModel(File dir)
{
directory = dir; // Hold the directory
rowCount=1;
}

//get the number of rows for the table to be prepared.
public int getRowCount()
{
return 1;
}

//get the column count.
public int getColumnCount()
{
return 5;
}

//get each of the table values at the specified row and column.
public Object getValueAt(int row, int column)
{
if (directory == null)
{
return null;
}

File fileSysEntity = new File(directory.getPath());
switch(column)
{
case 0: //name
return fileSysEntity.getName();

case 1: //size
return new Long(fileSysEntity.length());

case 2:
if(fileSysEntity.canRead())
{
return (new Boolean("true"));
}
else
{
return (new Boolean(false));
}

case 3:
if(fileSysEntity.canRead())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}

case 4:
if(fileSysEntity.isHidden())
{
return (new Boolean(true));
}
else
{
return (new Boolean(false));
}
default:
return "";
}
}

// get the column names to be used in the table header.
public String getColumnName(int column)
{
switch(column)
{
case 0:
return "Name";
case 1:
return "Size";
case 2:
return "Read";
case 3:
return "Write";
case 4:
return "Hidden";
default:
return "";
}
}

//get the class types of the entries in each of the table columns.
public Class getColumnClass(int column)
{
Class returnClass = Boolean.class;
if (column == 0 || column==1)
returnClass = String.class;
return returnClass;
}
}//end class Filemodel

Download

DeletingTool

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.BorderFactory;
class DeletingTool implements ActionListener
{
JFrame f;
JTextField tf;
JButton b1,b2,browse;
JLabel label,lb;
DeletingTool()
{
String labeltext="Enter the PATH of Folder/File to DELETE........."+"Eg.. f:/games to delete games folder in Drive f"+
"& f:/milan.txt to delete milan.txt in Drive f";
f=new JFrame("Deleting Tool");
tf=new JTextField("");
b1=new JButton("Delete");
b2=new JButton("Clear");
browse=new JButton("Browse");
lb=new JLabel(" Created By :- > Milan");
label=new JLabel(labeltext,JLabel.CENTER);
label.setBorder(BorderFactory.createTitledBorder("How To Do"));
f.setLayout(null);
tf.setBounds(40,40,265,40);
b1.setBounds(40,110,100,50);
b2.setBounds(200,110,100,50);
label.setBounds(40,170,265,80);
lb.setBounds(40,5,265,40);
browse.setBounds(125,260,80,40);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf);
f.add(b1);
f.add(b2);
f.add(label);
f.add(lb);
f.add(browse);

f.setSize(350,350);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
browse.addActionListener(this);
f.setLocation(400,200);
}

public static void main(String... s)
{
new DeletingTool();
}

public void actionPerformed(ActionEvent e)
{
JFileChooser chooser=new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(e.getActionCommand()=="Delete")
{
String path=tf.getText();
File f=new File(path);
if(!f.exists())
{
JOptionPane.showMessageDialog(null, "File/Folder Does not exist", "Are You MAD...", JOptionPane.ERROR_MESSAGE);
}
else
{
if(f.exists() && JOptionPane.showConfirmDialog(null,"Are you sure you want to delete", "Hi..", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
deleteFile(f);
JOptionPane.showMessageDialog(null, "Deleted", "Result", JOptionPane.INFORMATION_MESSAGE);
}
}
}

if(e.getSource()==browse)
{
int result=chooser.showOpenDialog(null);
if(result==chooser.APPROVE_OPTION)
{
tf.setText(chooser.getSelectedFile().getAbsolutePath());
//filename=chooser.getSelectedFile().getAbsolutePath();
}
}

if(e.getActionCommand()=="Clear")
{
tf.setText("");
}
}
public void deleteFile(File path) {
if( path.exists() ) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for(int i=0; i if(files[i].isDirectory()) {
deleteFile(files[i]);
} else {
files[i].delete();
}
}
}
}
path.delete();
}
}

Download

CrazyPad

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.text.*;
import java.awt.datatransfer.*;
import java.util.*;
import java.beans.*;
public class CrazyPad extends JFrame implements ActionListener,KeyListener
{
boolean flag=false;
String filename="";
File fname;
static JFrame f;
JMenuBar menubar;
JMenu m1,m2,m3,m4,m5,m6;
JMenuItem m1item1,m1item2,m1item3,m1item4;
JMenuItem m2item1,m2item2,m2item3,m2item4,m2item5;
JMenuItem m3item1,m3item2;

JMenuItem m5item1;
JCheckBoxMenuItem tool;

Color c=new Color(0,0,0);
JTextArea textarea;
JScrollPane sp;
JFileChooser chooser;
JToolBar toolbar;
JButton New,open,save,cut,copy,paste;
Icon n,o,s,ct,cp,p;
CrazyPad()
{
chooser=new JFileChooser();
f=new JFrame("CrazyPad1.0");
menubar=new JMenuBar();

m1=new JMenu("File");
m2=new JMenu("Edit");
m3=new JMenu("Format");

m5=new JMenu("About");
m6=new JMenu("View");

m1.setMnemonic('f');
m2.setMnemonic('e');
m3.setMnemonic('o');

m5.setMnemonic('u');
m6.setMnemonic('v');

//file menu
m1item1=new JMenuItem("New");
m1item2=new JMenuItem("Open");
m1item3=new JMenuItem("Save");
m1item4=new JMenuItem("Exit");

//edit menu
m2item1=new JMenuItem("Cut");
m2item2=new JMenuItem("Copy");
m2item3=new JMenuItem("Paste");
m2item4=new JMenuItem("SelectAll");
m2item5=new JMenuItem("Delete");

//format menu
m3item1=new JMenuItem("Color");
m3item2=new JMenuItem("Font");

//about menu
m5item1=new JMenuItem("About");

tool=new JCheckBoxMenuItem("Toolbar");

//setting the shortcuts
m1item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_MASK));
m1item2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,KeyEvent.CTRL_MASK));
m1item3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,KeyEvent.CTRL_MASK));
m1item4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,KeyEvent.ALT_MASK));

m2item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,KeyEvent.CTRL_MASK));
m2item2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,KeyEvent.CTRL_MASK));
m2item3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,KeyEvent.CTRL_MASK));
m2item4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,KeyEvent.CTRL_MASK));


m3item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,KeyEvent.CTRL_MASK));
m3item2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,KeyEvent.CTRL_MASK));


m5item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,KeyEvent.CTRL_MASK));

//adding the menus on menu bar
menubar.add(m1);
menubar.add(m2);
menubar.add(m3);
menubar.add(m6);
menubar.add(m5);

//adding menuitems on menu
m1.add(m1item1);
m1.add(m1item2);
m1.add(m1item3);
m1.addSeparator();
m1.add(m1item4);

m2.add(m2item1);
m2.add(m2item2);
m2.add(m2item3);
m2.addSeparator();
m2.add(m2item4);
m2.add(m2item5);

m3.add(m3item1);
m3.add(m3item2);

m5.add(m5item1);

m6.add(tool);

//listener to the menu items
m1item1.addActionListener(this);
m1item2.addActionListener(this);
m1item3.addActionListener(this);
m1item4.addActionListener(this);

m2item1.addActionListener(new CutCopyPasteListener());
m2item2.addActionListener(new CutCopyPasteListener());
m2item3.addActionListener(new CutCopyPasteListener());
m2item4.addActionListener(this);
m2item5.addActionListener(this);


m3item1.addActionListener(this);
m3item2.addActionListener(this);

m5item1.addActionListener(this);

tool.addActionListener(new viewListener());

//toolbar settings
toolbar=new JToolBar("Toolbar",SwingConstants.VERTICAL);
toolbar.setFloatable(false);
n=new ImageIcon("new.gif");
o=new ImageIcon("open.gif");
s=new ImageIcon("save.gif");
ct=new ImageIcon("cut.gif");
cp=new ImageIcon("copy.gif");
p=new ImageIcon("paste.gif");

New=new JButton(n);
open=new JButton(o);
save=new JButton(s);
cut=new JButton(ct);
copy=new JButton(cp);
paste=new JButton(p);

toolbar.add(New);
toolbar.add(open);
toolbar.add(save);
toolbar.add(cut);
toolbar.add(copy);
toolbar.add(paste);

New.setToolTipText("New");
open.setToolTipText("Open");
save.setToolTipText("Save");
cut.setToolTipText("Cut");
copy.setToolTipText("Copy");
paste.setToolTipText("Paste");

//toolbar listener
New.addActionListener(this);
open.addActionListener(this);
save.addActionListener(this);
cut.addActionListener(new CutCopyPasteListener());
copy.addActionListener(new CutCopyPasteListener());
paste.addActionListener(new CutCopyPasteListener());

f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new appCloseHandler());
Toolkit k=Toolkit.getDefaultToolkit();
Dimension d=k.getScreenSize();
int sw=d.width;
int sh=d.height;
f.setSize(400,400);
f.setLocation(sw/4,sh/4);
textarea=new JTextArea();
sp=new JScrollPane(textarea);

f.add(sp,BorderLayout.CENTER);
textarea.addKeyListener(this);
textarea.setFont(new Font("Comic Sans MS",Font.PLAIN,24));
f.setVisible(true);
f.setSize(401,401);
}

public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e)
{
flag=true;
}

public void newFile()
{
if(flag==true)
{
int result;
result=JOptionPane.showConfirmDialog(this,"Do You Want To Save The Changes?","New File",JOptionPane.YES_NO_CANCEL_OPTION);
if(result==JOptionPane.YES_OPTION)
{
saveFile();
}
else if(result==JOptionPane.CANCEL_OPTION)
{
return;
}
}
filename="";
flag=false;
textarea.setText("");
f.setTitle("Untitled");
}


public void saveFile()
{

if(filename.equals(""))
{
chooser= new JFileChooser();
int result;
result=chooser.showSaveDialog(this);
if(result==chooser.APPROVE_OPTION)
{
filename=chooser.getSelectedFile().getAbsolutePath();
fname=new File(filename);
if(fname.exists())
{
if(JOptionPane.showConfirmDialog(null,"File already exists.Do you want to Raplace?", "Hi..", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
madeFile();
}
else
{
filename="";
saveFile();
}
}
else
madeFile();
}

else
{
return;
}

}
else
madeFile();
}

public void madeFile()
{

try{
String data1=textarea.getText();
String[] a=data1.split("\n");
BufferedWriter bw=new BufferedWriter(new FileWriter(filename));
for(String data:a){
bw.write(data);
bw.newLine();}
bw.close();
flag=false;
fname=new File(filename);
f.setTitle(fname.getName());
}
catch(Exception e2){ System.out.println("can not write");}
}


public void openFile()
{
int result;
String data="";
if(flag==true)
{
if(JOptionPane.showConfirmDialog(null,"Do you want to save the changes?", "Open File", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
saveFile();
}
else
textarea.setText("");
result=chooser.showOpenDialog(this);
if(result==chooser.APPROVE_OPTION)
{
textarea.setText("");
filename=chooser.getSelectedFile().getAbsolutePath();
try{
BufferedReader in=new BufferedReader(new FileReader(filename));
while((data=in.readLine())!=null)
{
textarea.append(data);
textarea.append("\n");
}
}catch(Exception m){}

fname=new File(filename);
f.setTitle(fname.getName());
}
}


public void exitFile()
{
if(flag==true)
{
int result;
result=JOptionPane.showConfirmDialog(this,"Do You Want To Save The Changes?","File Exit",JOptionPane.YES_NO_CANCEL_OPTION);
if(result==JOptionPane.YES_OPTION)
{
saveFile();
}
else if(result==JOptionPane.CANCEL_OPTION)
{
return;
}
}
System.exit(0);
}


public void actionPerformed(ActionEvent e)
{
if(e.getSource()==m1item1 || e.getSource()==New)
{
newFile();
}
if(e.getSource()==m1item2 || e.getSource()==open)
{
openFile();
}
if(e.getSource()==m1item3 || e.getSource()==save)
{
saveFile();
}
if(e.getSource()==m1item4)
{
exitFile();
}
if(e.getSource()==m3item1)
{
c=JColorChooser.showDialog(null,"choose a color",c);
textarea.setForeground(c);
if(c==null)
c=Color.BLACK;
}
if(e.getSource()==m3item2)
new Myfont();
if(e.getSource()==m5item1)
{
String msg=" ----------------CrazyPad1.0--------------\nThis Pad Is Created purely in core java By Milan\n"+
" your suggestions are invited..."+"E-Mail me at:\n milankmr@gmail.com";
JOptionPane.showMessageDialog(null,msg);
}
if(e.getSource()==m2item4)
textarea.selectAll();
if(e.getSource()==m2item5)
textarea.replaceSelection("");
}
class Myfont
{
String[] font=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
JFrame f;
JPanel p;
JComboBox cb,cb1,cb2;
JLabel lb;
JLabel fontlb,stylelb,sizelb;
String fname="Comic Sans MS";
int style=Font.PLAIN;
int size=20;
JButton ok,cancel;
Myfont()
{
String lbtext="AaBbXxYyZz";
f=new JFrame("FontDialog");
p=new JPanel();
cb=new JComboBox();
cb1=new JComboBox();
cb2=new JComboBox();
fontlb=new JLabel("Font");
stylelb=new JLabel("Style");
sizelb=new JLabel("Size");
ok=new JButton("Ok");
cancel=new JButton("Cancel");
f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
f.add(p);
f.setVisible(true);
f.setSize(400,300);
lb=new JLabel(lbtext,JLabel.CENTER);
lb.setBorder(BorderFactory.createTitledBorder("Sample"));
lb.setFont(new Font(fname,style,size));
cb.setEditable(false);
cb1.setEditable(false);
cb2.setEditable(false);
p.setLayout(null);
cb.setBounds(10,50,170,40);
cb1.setBounds(200,50,80,40);
cb2.setBounds(310,50,60,40);
lb.setBounds(30,100,300,80);
fontlb.setBounds(80,20,80,40);
stylelb.setBounds(220,20,80,40);
sizelb.setBounds(320,20,80,40);
ok.setBounds(90,200,80,40);
cancel.setBounds(220,200,80,40);
p.add(cb);
p.add(lb);
p.add(cb1);
p.add(cb2);
p.add(fontlb);
p.add(stylelb);
p.add(sizelb);
p.add(ok);
p.add(cancel);
for(int i=0;i{
cb.addItem(font[i]);
}
for(int i=2;i<=72;i=i+2)
{
cb2.addItem(""+i);
}
Toolkit k=Toolkit.getDefaultToolkit();
Dimension ss=k.getScreenSize();
int sw=ss.width;
int sh=ss.height;
f.setLocation(sw/4,sh/4);
JFrame.setDefaultLookAndFeelDecorated(true);

cb1.addItem("Bold");
cb1.addItem("Italic");
cb1.addItem("Plain");
cb1.addItem("BoldItalic");
cb.addActionListener(new FontListener());
cb1.addActionListener(new StyleListener());
cb2.addActionListener(new SizeListener());
ok.addActionListener(new ButtonListener());
cancel.addActionListener(new ButtonListener());
}
class FontListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
fname=(String)cb.getSelectedItem();
lb.setFont(new Font(fname,style,size));
}
}
class StyleListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String temp=(String)cb1.getSelectedItem();
if(temp.equals("Bold"))
style=Font.BOLD;
if(temp.equals("Italic"))
style=Font.ITALIC;
if(temp.equals("Plain"))
style=Font.PLAIN;
if(temp.equals("BoldItalic"))
style=Font.BOLD+Font.ITALIC;
lb.setFont(new Font(fname,style,size));
}
}
class SizeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
size=Integer.parseInt((String)cb2.getSelectedItem());
lb.setFont(new Font(fname,style,size));
}
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ok)
{
textarea.setFont(new Font(fname,style,size));
f.setVisible(false);
}
if(e.getSource()==cancel)
{
f.setVisible(false);
}
}
}
}

class viewListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Dimension d;
int sw;
int sh;
if(e.getSource()==tool)
{
if(tool.isSelected())
{
f.add(toolbar,BorderLayout.WEST);
d=f.getSize();
sw=d.width;
sh=d.height;
f.setLocation(f.getLocation());
f.setSize(sw+1,sh+1);
}
else
{
f.remove(toolbar);
f.setLocation(f.getLocation());
d=f.getSize();
sw=d.width;
sh=d.height;
f.setSize(sw+1,sh+1);
}
}
}
}

class CutCopyPasteListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==m2item1 || e.getSource()==cut)
cutdata();
if(e.getSource()==m2item2 || e.getSource()==copy)
copydata();
if(e.getSource()==m2item3 || e.getSource()==paste)
pastedata();
}
public void cutdata()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String text =textarea.getSelectedText();
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, null);
text="";
textarea.replaceSelection(text);
}
public void copydata()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String text = textarea.getSelectedText();
if (text == null) text="";
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, null);
}
public void pastedata()
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor flavor = DataFlavor.stringFlavor;
if (clipboard.isDataFlavorAvailable(flavor))
{
try
{
String text = (String) clipboard.getData(flavor);
textarea.replaceSelection(text);
}
catch (IOException e4){System.out.println("error2");}
catch (UnsupportedFlavorException e3){System.out.println("error1");}
}
}
}

class appCloseHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
exitFile();
}
}

public static void main(String... s) throws Exception
{
new CrazyPad();
Date d = new Date();
JPanel datePanel = new JPanel();
JLabel label = new JLabel(d.toLocaleString());
datePanel.add(label);
f.add(datePanel,"South");
while(true)
{
d=new Date();
label.setText(""+d.toLocaleString());
}
}
}

Download

CalculatorPad

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class CalPad implements ActionListener
{
JFrame frame;
JPanel upperPanel;
JPanel lowerPanel;
JPanel buttonPanel;
JTextArea textArea;
JTextField display;
JScrollPane sp;
JLabel lb;
JButton button[]=new JButton[20];
Icon icon[]=new Icon[20];

static int count;
double opr1,opr2;
String lastoperator="";
double result;
static boolean saveflag=false;
String filename="";
File fname;

CalPad()
{
frame=new JFrame("Calculator ~~milan~~");

upperPanel=new JPanel();
lowerPanel=new JPanel();
buttonPanel=new JPanel();

textArea=new JTextArea();
Color c=new Color(0X4682B4);
textArea.setBackground(c);
textArea.setForeground(Color.white);
textArea.setFont(new Font("comic sans",Font.PLAIN,14));
textArea.setEditable(false);

//textArea.setText(format+"milan");
display=new JTextField("");
display.setBackground(Color.black);
display.setForeground(Color.green);
display.setFont(new Font("comic sans",Font.PLAIN,22));
display.setEditable(false);


lb=new JLabel(new ImageIcon("calculator1.gif"));
sp=new JScrollPane(textArea);
upperPanel.setLayout(null);
lb.setBounds(-10,0,270,50);
sp.setBounds(0,50,250,150);
display.setBounds(0,200,250,40);

upperPanel.add(lb);
upperPanel.add(sp);
upperPanel.add(display);


buttonPanel.setLayout(new GridLayout(5,4));

for(int i=0;i<20;i++)
{
icon[i]=new ImageIcon(i+".gif");
button[i]=new JButton(icon[i]);
buttonPanel.add(button[i]);
button[i].addActionListener(this);
}

setCalOff();



lowerPanel.setLayout(new BorderLayout());
lowerPanel.add(buttonPanel,BorderLayout.CENTER);

frame.setLayout(new GridLayout(2,1));
frame.add(upperPanel);
frame.add(lowerPanel);
frame.setSize(260,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String... s)
{
new CalPad();
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button[0])
save();
if(e.getSource()==button[1])
{
if(saveflag==false)
{
if(JOptionPane.showConfirmDialog(null,"Do You Want To Save?", "Hi..(milan)", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
save();
else
System.exit(0);
}
else
{
save();
System.exit(0);
}
}
if(e.getSource()==button[2])
setCalOn();
if(e.getSource()==button[3])
setCalOff();


if(e.getSource()==button[4])
show("1");
else if(e.getSource()==button[5])
show("2");
else if(e.getSource()==button[6])
show("3");
else if(e.getSource()==button[8])
show("4");
else if(e.getSource()==button[9])
show("5");
else if(e.getSource()==button[10])
show("6");
else if(e.getSource()==button[12])
show("7");
else if(e.getSource()==button[13])
show("8");
else if(e.getSource()==button[14])
show("9");
else if(e.getSource()==button[17])
show("0");

if(e.getSource()==button[16])
{
if(display.getText().indexOf(".")==-1)
{
display.setText(display.getText()+".");
textArea.append(".");
}
else{}
}



if(e.getSource()==button[7])
{
count++;
setopr1("+");
lastoperator="+";
textArea.append("+\n");
}

if(e.getSource()==button[11])
{
count++;
setopr1("-");
lastoperator="-";
textArea.append("-\n");
}

if(e.getSource()==button[15])
{
count++;
setopr1("*");
lastoperator="*";
textArea.append("*\n");
}

if(e.getSource()==button[19])
{
count++;
setopr1("/");
lastoperator="/";
textArea.append("/\n");
}


if(e.getSource()==button[18])
{
count++;
setopr1("=");
lastoperator="=";
display.setText(""+result);
textArea.append("\n----------------------\n");
textArea.append("="+result);
}

}

public void setopr1(String op)
{
if(count<=1)
{
opr1=Double.parseDouble(display.getText());
result=opr1;
}
else
{
if(!display.getText().equals(""))
{
opr2=Double.parseDouble(display.getText());
if(lastoperator.equals("+"))
{
result=result+opr2;
}
if(lastoperator.equals("-"))
{
result=result-opr2;
}
if(lastoperator.equals("*"))
{
result=result*opr2;
}
if(lastoperator.equals("/"))
{
result=result/opr2;
}
if(lastoperator.equals("="))
{
result=result;
display.setText(""+result);
}
}

else{}
}
display.setText("");
}


public void setData(double operand,String operator)
{
textArea.append(""+operand+operator);
textArea.append("\n");
}

public void setCalOn()
{
for(int i=0;i<20;i++)
{
if(i==2)
button[2].setEnabled(false);
else
button[i].setEnabled(true);
}
}

public void setCalOff()
{
for(int i=0;i<20;i++)
{
if(i==2)
button[i].setEnabled(true);
else
button[i].setEnabled(false);
}
resetCal();
}


public void resetCal()
{
textArea.setText("");
display.setText("");
result=0.0;
opr1=0.0;
opr2=0.0;
count=0;
}

public void show(String s)
{
if(display.getText().equals(""))
display.setText(s);
else
display.setText(display.getText()+s);
textArea.append(s);
}


public void save()
{

if(saveflag==false)
{
JFileChooser chooser= new JFileChooser();
int result;
result=chooser.showSaveDialog(null);
if(result==chooser.APPROVE_OPTION)
{
filename=chooser.getSelectedFile().getAbsolutePath();
fname=new File(filename);
if(fname.exists())
{
if(JOptionPane.showConfirmDialog(null,"File already exists.Do you want to Raplace?", "Hi..", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
madeFile(filename);
}
else{saveflag=false;save();}
}
else
madeFile(filename);
}
else
return;
}
else
madeFile(filename);
}

public void madeFile(String filename)
{
try{
String data1=textArea.getText();
String[] a=data1.split("\n");
BufferedWriter bw=new BufferedWriter(new FileWriter(filename));
for(String data:a)
{
bw.write(data);
bw.newLine();
}
bw.close();
fname=new File(filename);
}
catch(Exception e2){ System.out.println("can not write"+e2);}
String str=fname.getName();
JOptionPane.showMessageDialog(null,"Saved in :: "+str,"Success",JOptionPane.INFORMATION_MESSAGE);
saveflag=true;
}
}//end classs
Download