Thursday, October 14, 2010

My Search Tool

This is a program written in java that searches a file in the specific directory or in a Drive....



code::
//Search.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.io.*;
class Search implements ActionListener,Runnable
{
JFrame mainFrame;
JPanel rightPanel,mainPanel;
JPanel leftPanel;
JTextField tf1,tf2;
JButton jb;
int sw;
int sh;
JTable table;
DefaultTableModel model;
JScrollPane sp;
static int count=0;
Vector v=new Vector();
JComboBox cb;
JButton up,down;
JLabel temp;
JButton browse;
JCheckBox specific;
String pathtolook="";
JLabel dynamic;
ImageIcon icon;
JLabel progresslb;
JLabel imglb;
ImageIcon i;
Search()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
}

Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
sw=d.width;
sh=d.height;

mainFrame=new JFrame("Search");
leftPanel=new BackgroundPanel();
rightPanel=new JPanel();


jb=new JButton("search");
cb=new JComboBox();
File roots[]=File.listRoots();
for(int i=0;icb.addItem(roots[i]);
//cb.getEditor().getEditorComponent().setBackground(Color.gray);

Vector v=new Vector();
v.add("Name");
v.add("Directory");
v.add("Size");
v.add("Type");
v.add("Date Modified");

String col[]={"Name","Directory","Size","Type","DataModified"};





sp=new JScrollPane();
table=new JTable();
model=new DefaultTableModel(col,0);
table.setModel(model);

//table.setShowGrid(false);
//table.setShowHorizontalLines(true);
//table.setShowVerticalLines(false);

sp.setViewportView(table);
model.setColumnIdentifiers(v);


leftPanel.setLayout(null);

JLabel lb1=new JLabel("All or Part Name of the File:");
lb1.setBounds(20,150,140,20);
leftPanel.add(lb1);

tf1=new JTextField();
tf1.setBounds(20,170,140,20);
leftPanel.add(tf1);

JLabel lb2=new JLabel("A word or Phrase in the File:");
lb2.setBounds(20,200,140,20);
leftPanel.add(lb2);

tf2=new JTextField();
tf2.setBounds(20,220,140,20);
leftPanel.add(tf2);


JLabel lb3=new JLabel("Look In:");
lb3.setBounds(20,250,140,20);
leftPanel.add(lb3);

cb.setBounds(20,270,140,20);
leftPanel.add(cb);

jb.setBounds(55,310,80,30);
leftPanel.add(jb);

i=new ImageIcon("sd.gif");
imglb=new JLabel(i);
imglb.setBounds(70,400,71,74);
leftPanel.add(imglb);

browse=new JButton("Specific folder search");
browse.setEnabled(false);
//browse.setContentAreaFilled(false);
browse.setBounds(10,500,150,20);
leftPanel.add(browse);
browse.addActionListener(new BrowseListener());

specific=new JCheckBox("Specific Search");
specific.addActionListener(new BrowseListener());
specific.setBounds(30,350,100,20);
leftPanel.add(specific);
specific.setContentAreaFilled(false);

icon=new ImageIcon("pb1.gif");
progresslb=new JLabel(icon);


leftPanel.setBounds(0,0,180,sh-60);
rightPanel.setBounds(180,0,sw-180,sh-60);
sp.setBounds(0,0,sw-185,sh-60);

//leftPanel.setBackground(Color.gray);
rightPanel.setBackground(Color.white);
rightPanel.setLayout(null);
rightPanel.add(sp);

mainPanel=new JPanel();
mainPanel.setLayout(null);
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);

//mainFrame.setLayout(null);
mainFrame.add(mainPanel);
mainFrame.setSize(sw,sh-30);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jb.addActionListener(this);
}


class BrowseListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser jfilechooser = new JFileChooser();
jfilechooser.setFileSelectionMode(1);
if(e.getSource() == browse)
{
int i = jfilechooser.showOpenDialog(null);
if(i == 0)
{
pathtolook=jfilechooser.getSelectedFile().getAbsolutePath();
dynamic=new JLabel("Look In: "+jfilechooser.getSelectedFile().getAbsolutePath());
dynamic.setBounds(5,550,200,20);
leftPanel.add(dynamic);
leftPanel.updateUI();

}
}

if(e.getSource()==specific)
{
if(specific.isSelected())
{
cb.setEnabled(false);
browse.setEnabled(true);
}
else
{
cb.setEnabled(true);
browse.setEnabled(false);
leftPanel.remove(dynamic);
leftPanel.updateUI();
}
}

}

}

public void actionPerformed(ActionEvent e)
{
if(tf1.getText().equals("") && tf2.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Enter the filename to search", "What to search", 0);
}
else
{
progresslb.setBounds(10,600,160,13);
leftPanel.add(progresslb);
leftPanel.updateUI();
i=new ImageIcon("searchdog.gif");
imglb.setIcon(i);
if(specific.isSelected())
{
new Thread(this).start();
}
else
{
pathtolook=""+cb.getSelectedItem();
new Thread(this).start();
}
}
jb.setEnabled(false);
}

public void run()
{
addDataInTable(tf1.getText().equals("")?tf2.getText():tf1.getText(),pathtolook);
icon =new ImageIcon("pb2.gif");
progresslb.setIcon(icon);

i=new ImageIcon("sd.gif");
//imglb.setBounds(70,400,71,74);
imglb.setIcon(i);
JOptionPane.showMessageDialog(null,"Search Complete\n No. of Files and Directories found:"+count,"Complete",JOptionPane.PLAIN_MESSAGE);
}


public void addDataInTable(String dts,String rts)
{
File f=new File(rts);
File[] list=f.listFiles();
for(int i=0;i{
if(list[i].isDirectory() && !list[i].isHidden())
{
if(list[i].getName().contains(dts))
{
v=new Vector();
v.add(list[i].getName());
v.add(list[i].getParent());
v.add("A Directory");
v.add("directory");
Date date=new Date(list[i].lastModified());
v.add(date.toString());
model.insertRow(count,v);
count++;
}
addDataInTable(dts,list[i].getPath());
}
else
{
if(list[i].getName().contains(dts))
{
v=new Vector();
v.add(list[i].getName());
v.add(list[i].getParent());
v.add(""+(list[i].length()/1024)+"KB");
v.add("file");
Date date=new Date(list[i].lastModified());
v.add(date.toString());
model.insertRow(count,v);
count++;
}
}
}
}
public static void main(String... s)
{
new Search();
}
}

//BackgroundPanel.java
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

class BackgroundPanel extends JPanel
{
Image image;
public BackgroundPanel()
{
try
{
image = new ImageIcon("back2.PNG").getImage();
}
catch (Exception e) { /*handled in paintComponent()*/ }
}


public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
super.paintComponent(g);
if (image != null)
g.drawImage(image,0,0,null);

}
}

SearchTool


Tuesday, October 5, 2010

Pointers vs References...

Why java use references not pointers?????
To get the answer of this we have to go the low level that is the memory allocation for the object....

Where the Object is stored???
A quick answer::an Object is stored on the heap??

what is the Heap???
The heap is a large block of memory that Java uses to store objects........

How the things are Happening?????
When a new object is created, the necessary amount of space is set aside for it in the heap. The new operator returns a reference to the block of memory in the heap where the object is stored. The virtual machine is responsible for managing the heap and making sure that the same block of memory is not used for two different objects or arrays at the same time.
The exact size of the heap is system-dependent. However, the heap is finite on all systems. In some Java implementations, the heap can grow if more space is needed. On others the size of the heap is fixed when the virtual machine starts up....

suppose this is a heap actually this is a fragmented heap..
Whenever we starts our program we come with a heap fairly empty,and after running our program for some time some objects are created and some are garbage collected so we leave up with a frangmented heap..
(suppose redblocks are occupied by some object and gray ones are free..and each block represent a word of memory)




and for a while just leave the references and think that you have been provided with the direct pointers to the heap memory as in C ..so our scenario will look like this:
This is the same heap, with object variables shown as ovals. The arrows are pointers into the heap. Each object has at least one pointer (to its own data), and some have multiple pointers if they themselves contain references to other objects.Furthermore, one object may be pointed to from several different places. This interconnected web of pointers makes it very difficult to move objects in the heap, because you have to update all of the different pointers that can exist in hundreds of different objects, methods, and threads...

Now suppose an object is created which requires 4 words of memory ,,now as we can see on the heap there is no free 4 words contiguous memory for the object,So the Heap has to be Defragmented.and this is what a Defragmented Heap looks like::
This is the Frangmented Heap and now there is space for a four-word object. However, many — perhaps most — of the pointers are broken. Some now point to the wrong object. Others point to nowhere in particular. The VM can try to identify every reference to each moved object in the running program and update it with the new address of its data, but there can be thousands of these, and the operation can be extremely time consuming in a large program.

Now How the problem can be solved?????
One way to look at the problem is that references point to areas of different sizes in the heap. If you could somehow arrange it so that every object needed exactly the same amount of space in the heap, then fragmentation would not be a problem. As long as there was any free space at all,it could be used.

References TO the Rescue....
Of course, different objects do take different amounts of space, but references always take same amount of memory. The solution is to insert an extra block of references between the references in your source code and the heap. When an object is moved in the heap,only one link needs to be updated: the one between the offset table and the data in the heap. The many more pointers to the offset table do not need to be updated.
Now our scenario will look like this::

So,we are provided with reference ,,not the direct pointer to the heap,another reason may be the security or platform independence to give the preference to the reference variables over pointers..........

compilation gotcha in java6 vs java7

Compiling all the files in a folder for a java programmer is a routine job ,,so what we do we go to required directory and say javac*.java and all the java files get compiled...
now suppose we are at e:\javapro and we want to compile all the java files present in
f:\javapro so what we will do,,we will go to f:\javapro in the prompt ,and then we will say javac *.java....

this is what what we do when we are using upto java7
now from java7 we can compile all the files in the different folders form the different location....
again suppose we are at e:\javapro and want to compile all the java files present at f:\javapro ,,so in java7 we will just say::

javac "f:\javapro\*.java";
and all the files will get compiled........
caution::quotes are necessary.......

but with java6 it will give the error::
file not found::f:\javapro\*.java

Monday, October 4, 2010

Table Viewer

This is Table viewer by which you can see the records of your table in your dsn with a scrollbar provided at the bottom of the frame....

Enter your DSN::



Now your can see the Name of the tables present in your dsn,select the table and go....



This is how you will see the recordes in your table.....



Your can download this from::
Download

Sunday, October 3, 2010

VirtualDosPrompt

This is the Virtual Dos Prompt created in java,having functionality like compiling the java files,running the class file ,seeing the directory,renaming the file or directory,and some thing more,,you can use help command to see the list of command available......



code::
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.awt.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.util.*;
class VirtualDosPrompt
{
JFrame f;
MyTextArea ta;
int length;
JScrollPane sp;
String curpath="";
boolean flag=true;
String fileName="";
VirtualDosPrompt()
{
f=new JFrame("Virtual DOS-Prompt");
ta=new MyTextArea();
ta.setBackground(Color.black);
ta.setForeground(Color.white);
ta.setFont(new Font("lucida console",Font.PLAIN,14));
((JTextComponent)ta).setCaretColor(Color.white);
ta.setLineWrap(true);
curpath=System.getProperty("user.dir")+">";

ta.setText(curpath);
length=curpath.length();
ta.setCaretPosition(length);
sp=new JScrollPane(ta);


f.add(sp);
f.setSize(670,340);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(100,100);
ta.addKeyListener(new MyTextAreaListener());
}
public static void main(String... s)
{
new VirtualDosPrompt();
}

class MyTextArea extends JTextArea
{
MyTextArea()
{
super();
}
MyTextArea(String str)
{
super(str);
}
public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
{
if(ta.getCaretPosition()>length)
return super.processKeyBinding(ks,e,condition,pressed);
else
{
if(e.getKeyCode()==e.VK_BACK_SPACE || e.getKeyCode()==e.VK_LEFT || e.getKeyCode()==e.VK_HOME || e.getKeyCode()==e.VK_DELETE || ta.getCaretPosition()return false;
else
return super.processKeyBinding(ks,e,condition,pressed);
}
}
}//end inner class

class MyTextAreaListener implements KeyListener
{
char c;
String s="";

public void keyPressed(KeyEvent ke)
{
c=ke.getKeyChar();
if(c=='\n' && flag==true)
{
String temp=ta.getText();
int index=temp.lastIndexOf(">");
s=temp.substring(index+1);
performAction(s.trim(),ke);
s="";
}
if(ke.isControlDown() && flag==false)
{
if(ke.getKeyCode()==ke.VK_S)
nowSaveFile(fileName);
else
{}
}
}
public void keyTyped(KeyEvent ke)
{}
public void keyReleased(KeyEvent ke)
{}

public void performAction(String cmd,KeyEvent ke)
{
if(cmd.equals("exit"))
{
System.exit(0);
}
else if(cmd.equals("cls"))
{
ta.setText("");
ta.setText(curpath);
length=curpath.length();
}
else if(cmd.equals("dir"))
{
showDirDetail();
}
else if(cmd.equals("info"))
{
showInfo();
}
else if(cmd.endsWith(":"))
{
changeDrive(cmd);
}
else if(cmd.equals("cd.."))
{
getParentDirectory();
}
else if(cmd.equals("cd\\"))
{
goToRoot();
}
else if(cmd.startsWith("cd"))
{
changeDirectory(cmd);
}
else if(cmd.startsWith("mkdir"))
{
makeDirectory(cmd);
}
else if(cmd.startsWith("del"))
{
deleteDirectory(cmd);
}
else if(cmd.equals("javac *.java"))
{
compileAll(cmd);
}
else if(cmd.startsWith("javac"))
{
compileJavaFile(cmd);
}
else if(cmd.startsWith("java"))
{
runJavaProgram(cmd);
}
else if(cmd.startsWith("bg"))
{
changeBackGroundColor(cmd);
}
else if(cmd.startsWith("fg"))
{
changeForeGroundColor(cmd);
}
else if(cmd.equals("reset"))
{
resetAll();
}
else if(cmd.startsWith("help") || cmd.equals("?"))
{
showHelp();
}
else if(cmd.equalsIgnoreCase("jinfo"))
{
showJavaInfo();
}
else if(cmd.equalsIgnoreCase("osinfo"))
{
showOSInfo();
}
else if(cmd.startsWith("create file"))
{
flag=false;
createFile(cmd,ke);
}
else if(cmd.startsWith("ren"))
{
renameFile(cmd);
}
else if(cmd.equalsIgnoreCase("wv"))
{
ta.setBackground(Color.white);
ta.setForeground(Color.black);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.black);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("nv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.white);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.white);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("ov"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.orange);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.orange);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("yv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.yellow);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.yellow);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("gv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.green);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.green);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("rv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.red);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.red);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("cv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.cyan);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.cyan);
length=ta.getText().length();
}
else if(cmd.equalsIgnoreCase("grv"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.gray);
ta.append("\n"+curpath);
((JTextComponent)ta).setCaretColor(Color.gray);
length=ta.getText().length();
}
else
{
ta.append("\ncommand not found");
ta.append("\nSee help or ? for command list\n");
ta.append(curpath);
length=ta.getText().length();
}
}

public void resetAll()
{
ta.setBackground(Color.black);
ta.setForeground(Color.white);
((JTextComponent)ta).setCaretColor(Color.white);
ta.append("\n"+"DOs-Prompt Resetted");
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void changeBackGroundColor(String cmd)
{
String bg=cmd.substring(3);
Color c=getColor(bg);
ta.setBackground(c);
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void changeForeGroundColor(String cmd)
{
String fg=cmd.substring(3);
Color c=getColor(fg);
ta.setForeground(c);
ta.append("\n"+curpath);
length=ta.getText().length();
}

public Color getColor(String bg)
{
Color c=new Color(0,0,0);
if(bg.equalsIgnoreCase("red"))
c=Color.red;
else if(bg.equalsIgnoreCase("white"))
c=Color.white;
else if(bg.equalsIgnoreCase("gray"))
c=Color.gray;
else if(bg.equalsIgnoreCase("lightgray"))
c=Color.lightGray;
else if(bg.equalsIgnoreCase("darkgray"))
c=Color.darkGray;
else if(bg.equalsIgnoreCase("black"))
c=Color.black;
else if(bg.equalsIgnoreCase("pink"))
c=Color.pink;
else if(bg.equalsIgnoreCase("orange"))
c=Color.orange;
else if(bg.equalsIgnoreCase("yellow"))
c=Color.yellow;
else if(bg.equalsIgnoreCase("green"))
c=Color.green;
else if(bg.equalsIgnoreCase("magenta"))
c=Color.magenta;
else if(bg.equalsIgnoreCase("cyan"))
c=Color.cyan;
else if(bg.equalsIgnoreCase("blue"))
c=Color.blue;
else if(bg.equalsIgnoreCase("default"))
{
ta.setBackground(Color.black);
ta.setForeground(Color.white);
return null;
}
else
{
ta.append("\n"+"This Color is not present,see help for bg");
}
return c;
}

public void renameFile(String cmd)
{
String cp=curpath.substring(0,curpath.length()-1);
String token[]=cmd.split(" ");
if(token.length!=3)
ta.append("\nren takes two arguments,sourcename and desname");
else
{
String sourceName=token[1];
String desName=token[2];

if(sourceName.indexOf(File.separator)==-1)
sourceName=cp+File.separator+sourceName;
if(desName.indexOf(File.separator)==-1)
desName=cp+File.separator+desName;

File f1=new File(sourceName);
File f2=new File(desName);

System.out.println("f1 name:"+f1);
System.out.println("f2 name:"+f2);

if(f1.exists())
{
f1.renameTo(f2);
if(sourceName.charAt(0)==desName.charAt(0))
ta.append("\nFile Renamed");
else
ta.append("\nFile Renamed and moved");
}
else
ta.append("\n source file does not exists");
}
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void nowSaveFile(String fileName)
{
String data=ta.getText().substring(length+System.getProperty("line.separator").toString().length()-1);
String[] a=data.split("\n");
try
{
BufferedWriter bw=new BufferedWriter(new FileWriter(fileName));
for(String str:a)
{
bw.write(str);
bw.newLine();
}
bw.close();
flag=true;
ta.append("\nFile created");
ta.append("\n"+curpath);
length=ta.getText().length();
}
catch(Exception e)
{
System.out.println("file creation exception"+e);
ta.append("\n"+"can not create file");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}

public void createFile(String cmd,KeyEvent ke)
{
flag=false;
String cp=curpath.substring(0,curpath.length()-1);
String tempfileName=cmd.substring(12);
if(tempfileName.indexOf(File.separator)==-1)
{
fileName=cp+File.separator+tempfileName;
}
else
{
fileName=tempfileName;
}
if(new File(fileName).exists())
{
ta.append("\nFile already exists");
ta.append("\n"+curpath);
flag=true;
}
length=ta.getText().length();
}

public void showOSInfo()
{
ta.append("\n\nOperating system name:-" + System.getProperty("os.name").toString());
ta.append("\nOperating system architecture:-" + System.getProperty("os.arch").toString());
ta.append("\nOperating system version:-" + System.getProperty("os.version").toString());
ta.append("\nFile separator (" + "/" + " on UNIX):-" + System.getProperty("file.separator").toString());
ta.append("\nPath separator (" + ":" + " on UNIX):-" + System.getProperty("path.separator").toString());
ta.append("\nLine separator :-" + System.getProperty("line.separator").toString());
ta.append("\nUser's account name:-" + System.getProperty("user.name").toString());
ta.append("\nUser's home directory:-" + System.getProperty("user.home").toString());
ta.append("\nUser's current working directory:-" + System.getProperty("user.dir").toString());
ta.append("\n\n"+curpath);
length=ta.getText().length();
}


public void showJavaInfo()
{
ta.append("\n\nJava Runtime Environment version:-" + System.getProperty("java.version").toString());
ta.append("\nJava Runtime Environment vendor:-" + System.getProperty("java.vendor").toString());
ta.append("\nJava vendor URL:-" + System.getProperty("java.vendor.url").toString());
ta.append("\nJava installation directory:-" + System.getProperty("java.home").toString());
ta.append("\nJava Virtual Machine specification version:-" + System.getProperty("java.vm.specification.version").toString());
ta.append("\nJava Virtual Machine specification vendor:-" + System.getProperty("java.vm.specification.vendor").toString());
ta.append("\nJava Virtual Machine specification name:-" + System.getProperty("java.vm.specification.name").toString());
ta.append("\nJava Virtual Machine implementation version:-" + System.getProperty("java.vm.version").toString());
ta.append("\nJava Virtual Machine implementation vendor:-" + System.getProperty("java.vm.vendor").toString());
ta.append("\nJava Virtual Machine implementation name:-" + System.getProperty("java.vm.name").toString());
ta.append("\nJava Runtime Environment specification version:-" + System.getProperty("java.specification.version").toString());
ta.append("\nJava Runtime Environment specification vendor:-" + System.getProperty("java.specification.vendor").toString());
ta.append("\nJava Runtime Environment specification name:-" + System.getProperty("java.specification.name").toString());
ta.append("\nJava class format version number:-" + System.getProperty("java.class.version").toString());
ta.append("\nJava class path:-" + System.getProperty("java.class.path").toString());
//ta.append("\nJava Library Path:-" + System.getProperty("java.library.path").toString());
ta.append("\n\n"+curpath);
length=ta.getText().length();
}

public void runJavaProgram(String cmd)
{
String cp=curpath.substring(0,curpath.length()-1);
String fileName=cmd.substring(5);
String str="";
String x=new String("\"");
if(fileName.indexOf(File.separator)==-1)
{
if(cp.length()==3)
{
compileandrun("java -cp "+x+cp.substring(0,2)+x+" "+fileName);
}
else
compileandrun("java -cp "+x+cp+x+" "+fileName);
}
else
{
ta.append("\n"+"Can not run in this way");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}


public void compileAll(String cmd)
{
String cp=curpath.substring(0,curpath.length()-1);
String str=cp+File.separator+"*.java";
String x=new String("\"");
compileandrun("javac "+x+str+x);
}

public void compileJavaFile(String cmd)
{
String cp=curpath.substring(0,curpath.length()-1);
String fileName=cmd.substring(6);
String str="";

if(fileName.indexOf(File.separator)==-1)
{
str=cp+File.separator+fileName;
}
else
{
str=fileName;
}
File f=new File(str);
String x=new String("\"");
if(!f.exists())
{
ta.append("\n"+"File doesn't exists");
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
compileandrun("javac "+x+str+x);
}
}

public void compileandrun(String str)
{
System.out.println("command 2 run:"+str);
String s="";
try
{
Process p = Runtime.getRuntime().exec(str);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null)
{
ta.append("\n"+s);
}
while ((s = stdError.readLine()) != null)
{
ta.append("\n"+s);
}
}
catch(Exception e)
{
System.out.println("Exception in compilation"+e);
e.printStackTrace();
}
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void deleteDirectory(String cmd)
{
String dirName=cmd.substring(4);
String cp=curpath.substring(0,curpath.length()-1);
String temp="";
if(dirName.indexOf(File.separator)==-1)
temp=cp+File.separator+dirName;
else
temp=dirName;
File path=new File(temp);
if(!path.exists())
{
ta.append("\n"+"Directory doesn't exists");
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
ta.append("\n"+"Deleteing......");
try
{
deleteDir(path);
ta.append("\n"+"Deletion successful");
ta.append("\n"+curpath);
length=ta.getText().length();
}
catch(Exception e)
{
ta.append("\n"+"Can not delete this directory");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}
}

public void deleteDir(File path) {
if (path.isDirectory())
{
File[] files = path.listFiles();
for(int i=0; i {
if(files[i].isDirectory())
{
deleteDir(files[i]);
}
else
{
files[i].delete();
}
}
}
path.delete();
}

public void makeDirectory(String cmd)
{
String dirName=cmd.substring(6);
String cp=curpath.substring(0,curpath.length()-1);
String str="";
if(dirName.indexOf(File.separator)==-1)
str=cp+File.separator+dirName;
else if(dirName.indexOf(File.separator)!=-1)
str=dirName;

File f=new File(str);
if(f.exists())
{
ta.append("\n"+"Directory Exists");
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
try
{
f.mkdir();
if(f.exists())
{
ta.append("\n"+"Directory created");
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
ta.append("\n"+"Directory can't be created");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}
catch(Exception e)
{
System.out.println("can't create directory");
}
}

}


public void goToRoot()
{
String root=curpath.substring(0,3);
curpath=root+">";
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void getParentDirectory()
{
if(curpath.length()>4)
{
String cp=curpath.substring(0,curpath.length()-1);
File f=new File(cp);
String parent=""+f.getParent();
curpath=parent+">";
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
ta.append("\n"+curpath);
length=ta.getText().length();
}
}
public void showDirDetail()
{
String path=curpath.substring(0,curpath.length()-1);
int nof=0;
int nod=0;
float tfl=0;
long tdl=0;
File f=new File(path);
File[] list=f.listFiles();
ta.append("\n");
ta.append("Type:"+"\t"+"Size:"+"\t"+"\t"+"Name:");
for(int i=0;i{
ta.append("\n");
if(list[i].isDirectory())
{
//tdl+=getDirectorySize(list[i]);
ta.append(""+"\t"+"\t"+"\t"+list[i].getName());
nod++;
}
else
{
float length=0;
tfl+=list[i].length();
if(list[i].length()>9999)
{
length=list[i].length()/1024;
ta.append(""+"\t"+length+" KB"+"\t"+"\t"+list[i].getName());
}
else
ta.append(""+"\t"+list[i].length()+" bytes"+"\t"+"\t"+list[i].getName());
nof++;
}
}
ta.append("\n");
ta.append("Number of Files:"+nof+"\t"+" Total Length:"+tfl/(1024*1024)+" MB");
ta.append("\n");
ta.append("Number of Directories:"+nod);
//ta.append("\nTotal size iof this Directory:"+(tfl+tdl)/1024+" KB");
ta.append("\n"+curpath);
length=ta.getText().length();
}

public void showInfo()
{
ta.append("\n");
ta.append("*******************************************************************\n");
ta.append("Project Name: "+"Virtual Dos-Prompt\n");
ta.append("Creatred By: "+"Er. Milan Kumar\n");
ta.append("Version : "+"v1.0\n");
ta.append("Devoted to: "+"JAVA\n");
ta.append("*******************************************************************\n");
ta.append(curpath);
length=ta.getText().length();
}

public long getDirectorySize(File path)
{
long size=0;
File[] list=path.listFiles();
for(int i=0;i{
if(list[i].isFile())
size+=list[i].length();
else
getDirectorySize(list[i]);
}
return size;
}

public void changeDrive(String drive)
{
FileSystemView fsv=FileSystemView.getFileSystemView();
File f=new File(drive+File.separator);
if(fsv.isDrive(f))
{
curpath=drive+File.separator+">";
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
ta.append("\n"+"No such drive on the system");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}

public void changeDirectory(String cmd)
{
String str=cmd.substring(2).trim();
String cp=curpath.substring(0,curpath.length()-1);
boolean check=sfd(cp,str);
if(check==true)
{
if(curpath.length()>4)
curpath=cp+File.separator+str+">";
else
curpath=cp+str+">";
ta.append("\n"+curpath);
length=ta.getText().length();
}
else
{
ta.append("\nno such directory exits");
ta.append("\n"+curpath);
length=ta.getText().length();
}
}

public boolean sfd(String dir,String temp)
{
File f=new File(dir);
File ch[]=f.listFiles();
for(int i=0;i{
if(ch[i].getName().equalsIgnoreCase(temp) && ch[i].isDirectory())
return true;
}
return false;
}

public void showHelp()
{
ta.append("\n");
ta.append("--------------|------------------------------|-----------------------------\n");
ta.append(" COMMAND | MEANING | EXAMPLE\n");
ta.append("--------------|------------------------------|-----------------------------\n");
ta.append(" javac | Compile the java Program | javac Test.java\n");
ta.append(" javac *.java | Compile all the java files | javac *.java\n");
ta.append(" java | Run the .class file | java Test\n");
ta.append(" cls | Clear the screen | cls\n");
ta.append(" dir | shows the Directory | dir\n");
ta.append(" info | Shows the info of the prgm | info\n");
ta.append(" cd.. | Change Dir(Parent Dir) | cd..\n");
ta.append(" cd\\ | Change Dir to root | cd\\ \n");
ta.append(" mkdir | Make Directory | mkdir dirName or path\n");
ta.append(" del | Delete | del fileName,DirName,or Path\n");
ta.append(" bg | Background Color | bg red\n");
ta.append(" fg | Foreground COlor | fg black\n");
ta.append(" wv | White Video | wv\n");
ta.append(" nv | Normal Video | nv\n");
ta.append(" ov | Orange Video | ov\n");
ta.append(" yv | Yellow Video | yv\n");
ta.append(" gv | Green Video | gv\n");
ta.append(" rv | Red Video | rv\n");
ta.append(" cv | Cyan Video | cv\n");
ta.append(" grv | Gray Video | grv\n");
ta.append(" jinfo | Java Info | jinfo\n");
ta.append(" osinfo | Operating Sys Info | osinfo\n");
ta.append(" ? or help | Shows Help | ? or help\n");
ta.append(" create file | create file,ctrl+s to create | create file milan.txt\n");
ta.append(" ren | Rename file | ren name1.txt name2.txt\n");
ta.append("\n"+curpath);
length=ta.getText().length();
}

}//end inner class
}//end outer class

caution::i have compiled it with jdk1.7,so if you are having trouble recompile it with your version...........
some more commands are yet to be added in the next version....

Download vdp.jar

Download vdp.rar

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