<div style='background-color: none transparent;'></div>

World News

Entertainment

Example of keySet method of HashMap.

HashMapKeySet.java

package net.roseindia.java;

import java.util.HashMap;

import java.util.Set;

public class HashMapKeySet {

public static void main(String[] arr) {

/* Create object of HashMap */

HashMap obHashMap = new HashMap();

/* Strore value in HashMap */

obHashMap.put(new Integer(1), "AAA");

obHashMap.put(new Integer(2), "BBB");

obHashMap.put(new Integer(3), "CCC");

obHashMap.put(new Integer(4), "DDD");

obHashMap.put(new Integer(5), "EEE");

/* Create a set of keys of hashmap */

Set obKeySet = obHashMap.keySet();

System.out.println("Set of Keys : " + obKeySet); } }
Continue Reading | comments

Retrieving XML Data Using GWT

package com.google.gwt.sample.simplexml.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class SimpleXML implements EntryPoint {
private static final String XML_LABEL_STYLE = "xmlLabel";
private static final String USER_TABLE_LABEL_STYLE = "userTableLabel";
private static final String USER_TABLE_STYLE = "userTable";
private static final String NOTES_STYLE = "notes";

public void onModuleLoad() {
RequestBuilder requestBuilder = new
RequestBuilder(RequestBuilder.GET,"customerRecord.xml");
try {
requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
requestFailed(exception);
}
public void onResponseReceived(Request request, Response response){
renderXML(response.getText());
}
});
} catch (RequestException ex) {
requestFailed(ex);
}
}
private FlexTable createOrderTable(FlowPanel xmlParsed, String label){
HTML orderTableLabel = new HTML("

" + label);
xmlParsed.add(orderTableLabel);
FlexTable orderTable = new FlexTable();
orderTable.setStyleName(USER_TABLE_STYLE);
orderTable.setBorderWidth(3);
orderTable.getRowFormatter().setStyleName(0, USER_TABLE_LABEL_STYLE);
orderTable.setText(0, 0, "Employee ID");
orderTable.setText(0, 1, "Firstname");
orderTable.setText(0, 2, "Lastname");
orderTable.setText(0, 3, "City");
orderTable.setText(0, 4, "State");
orderTable.setText(0, 5, "Zip");
xmlParsed.add(orderTable);
return orderTable;
}
private void customerPane(String xmlText, FlowPanel xmlParsed) {
Document customerDom = XMLParser.parse(xmlText);
Element customerElement = customerDom.getDocumentElement();
XMLParser.removeWhitespace(customerElement);

String nameValue = getElementTextValue(customerElement, "name");
String title = "

" + nameValue + "

";
HTML titleHTML = new HTML(title);
xmlParsed.add(titleHTML);

String notesValue = getElementTextValue(customerElement, "notes");
Label notesText = new Label();
notesText.setStyleName(NOTES_STYLE);
notesText.setText(notesValue);
xmlParsed.add(notesText);

FlexTable pendingTable =
createOrderTable(xmlParsed, "Employee Details");
NodeList orders =
customerElement.getElementsByTagName("order");
int pendingRowPos = 0;
int completedRowPos = 0;
System.out.println(orders.getLength());
for (int i = 0; i < orders.getLength(); i++) {
Element order = (Element) orders.item(i);
HTMLTable table;
int rowPos;
if (order.getAttribute("status").equals("pending")) {
table = pendingTable;
rowPos = ++pendingRowPos;
} else {
table = pendingTable;
rowPos = ++pendingRowPos;
}
int columnPos = 0;
fillInOrderTableRow(customerElement, order, table, rowPos, columnPos);
}
}

private void fillInOrderTableRow
(Element customerElement, Element order,
HTMLTable table, int rowPos, int columnPos)
{
String orderId = order.getAttribute("id");
table.setText(rowPos, columnPos++, orderId);

Element item = (Element)
order.getElementsByTagName("item").item(0);
String itemUPC = item.getAttribute("Firstname");
String itemName = item.getFirstChild().getNodeValue();
Label itemLabel = new Label(itemUPC);
itemLabel.setTitle(itemName);
table.setWidget(rowPos, columnPos++, itemLabel);

String orderedOnValue = getElementTextValue
(customerElement, "Lastname");
table.setText(rowPos, columnPos++, orderedOnValue);

Element address = (Element)
order.getElementsByTagName("address").item(0);
XMLParser.removeWhitespace(address);
NodeList lst = address.getChildNodes();
for (int j = 0; j < lst.getLength(); j++) {
Element next = (Element) lst.item(j);
String addressPartText = next.getFirstChild().getNodeValue();
table.setText(rowPos, columnPos++, addressPartText);
}

}
private String getElementTextValue(Element parent, String elementTag){
return parent.getElementsByTagName(elementTag).item(0)
.getFirstChild().getNodeValue();
}
private void renderXML(String xmlText) {
final TabPanel tab = new TabPanel();
final FlowPanel xmlSource = new FlowPanel();
final FlowPanel xmlParsed = new FlowPanel();
tab.add(xmlParsed, "Employee");
tab.add(xmlSource, "XML");
tab.selectTab(0);
RootPanel.get().add(tab);
xmlPane(xmlText, xmlSource);
customerPane(xmlText, xmlParsed);
}

private void requestFailed(Throwable exception) {
Window.alert("Failed to send the message: "
+ exception.getMessage());
}
private void xmlPane(String xmlText, final FlowPanel xmlSource) {
xmlText = xmlText.replaceAll("<", "<");
xmlText = xmlText.replaceAll(">", ">");
Label xml = new HTML("
" + xmlText + "
", false);
xml.setStyleName(XML_LABEL_STYLE);
xmlSource.add(xml);
}
}
Step2:-Create a xml file named customerRecord.xml.

customerRecord.xml



Girish Tewari
Roseindia.net Rohini


Bronze Sword

Haldwani
Uttaranchal
263126

Tewari



Mahendra Singh Dhoni
Roseindia.net Rohini



Bronze Sword

Lucknow
UttarPradesh
263139

Tewari



Step3:-Create html file named SimpleXML.html





Simple XML Example




Retrieving XML Data Using GWT



Example of loading an XML file from the server.




Another way for running this example is to download this example, Extract it and put the extracted folder in the GWT directory. Place this extracted folder in the samples directory of the GWT toolkit. Just double click on the cmd SimpleXML-shell.cmd to view the output of the program.

Continue Reading | comments

sql php code



$host = "localhost";
$user = "root";
$password = "root";
$database = "komal";
$connection = mysql_connect($host,$user,$password)
or die("Could not connect: ".mysql_error());
mysql_select_db($database,$connection)
or die("Error in selecting the database:".mysql_error());
$array = array(1,2,3,4);
foreach ($array as $value){
$sql="Select * from stu where id =".$value;
$sql_result=mysql_query($sql,$connection)
or exit("Sql Error".mysql_error());
$sql_num=mysql_num_rows($sql_result);
echo "";
echo "";
echo "";
echo "";
while($sql_row=mysql_fetch_array($sql_result)) {
$id=$sql_row["id"];
$name=$sql_row["name"];
echo "";
echo "";
}
echo "
Id Name
".$id."".$name."

";
}
?>

Continue Reading | comments

Java read file line by line

import java.io.*;

public class ReadFile {
public static void main(String[] args) throws Exception {

File f = new File("C:/Hello.txt");
if (!f.exists() && f.length() < 0) {
System.out.println("The specified file does not exist");
} else {
FileReader fr = new FileReader(f);
BufferedReader reader = new BufferedReader(fr);
String st = "";
while ((st = reader.readLine()) != null) {
System.out.println(st);
}
}
}
}
Continue Reading | comments

Java write to file line by line

import java.io.*;

class FileWrite {
public static void writeToFile(String text) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
"C:/new.txt"), true));
bw.write(text);
bw.newLine();
bw.close();
} catch (Exception e) {
}
}

public static void main(String[] args) throws Exception {
String st1 = "Hello";
String st2 = "Where there is will, there is a way";

writeToFile(st1);
writeToFile(st2);

System.out.println("File created successfully!");
}
}
Continue Reading | comments

Simple java program

Write a program that prints the following pattern:

*
***
*****
*******
*****
***
*


public class Print{
public static void main(String[] args){
int i=1;
int j;
while(i<=7){
for(j=1;j<=i;j++)
System.out.print("*");
i=i+2;
System.out.println();
}
i=5;
while(i>=1){
for(j=1;j<=i;j++)
System.out.print("*");
i=i-2;
System.out.println();
}
}
}
Continue Reading | comments

PHP displaying the time and date into your timezone


ECHO "Date using date()fucntion is:"."
";

echo date("M d Y H:i:s",mktime(0,0,0,1,1,1998))."
";

ECHO "Date using gmdate()fucntion is:"."
";

echo gmdate("M d Y H:i:s",mktime(0,0,0,1,1,1998))."
";

?>
Continue Reading | comments

ASCII Table

ASCII Table

session_start();
$table = "";
$table .= "
";
$table .= "";
$table .= "";
$table .= "";
$table .= "";

$table .= "";
for($count = 1; $count <= 256; $count++)
{
$table .= "";
$table .= "";
if($count % 8 == 0) $table .= "";
}
$table .= "";
$table .= "
";
$table .= "";
$table .= " A S C I I - T a b l e";
$table .= "
";
$table .= "
";
$table .= "";
$table .= "
";
$table .= $count;
$table .= "
";
$table .= chr($count);
$table .= "
";
?>


Geerson - Ascii table






Continue Reading | comments

Strings sample source codes

Trim Function

Left - ltrim() function

$text = "\t\tThese are a few words :) ... ";
$trimmed = ltrim($text);
// $trimmed = "These are a few words :) ... "
$trimmed = ltrim($text," \t.");
// $trimmed = "These are a few words :) ... "
$clean = ltrim($binary,"\0x00..\0x1F");
// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)

?>

Right - rtrim() function

$text = "\t\tThese are a few words :) ... ";
$trimmed = rtrim($text);
// $trimmed = "\t\tThese are a few words :) ..."
$trimmed = rtrim($text," \t.");
// $trimmed = "\t\tThese are a few words :)"
$clean = rtrim($binary,"\0x00..\0x1F");
// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)

?>
Continue Reading | comments

Parsing a Query String

Parsing a Query String

$str = "first=value&arr[]=foo bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>
Continue Reading | comments

Calendar for any month any year

Calendar for any month any year


#
# *** Set time stamp.Check for month requested(value from request form)
# *** If no value has been set then make it for current month
#
if(!$year){$year=2000; }
if(!$req_month || $req_month=="none")
{
$dt_and_tm=time();
}
else
{
$dt_and_tm=mktime(0,0,0,$req_month,1,$year);
}
#
# *** Find out the month number from the time stamp we just created
# *** Find out the day of the week from the same(0 to 6 for Sunday to
# *** Saturday) add "1" so that it becomes 1 to 7
#

$month=date("n",$dt_and_tm);
$week_day=date("w",$dt_and_tm)+1;
#
# *** Set number days in requested month
#
if($month==1 || $month==3 || $month==5 || $month==7 || $month==8 || $month==10 ||
$month==12)
{
$no_of_days=31;
}
elseif($month==4 || $month==6 || $month==9 || $month==11)
{
$no_of_days=30;
}
#
# *** If the month requested is Feb. Check whether it is Leap Year
#
elseif($month==2)
{
if(date("L",$dt_and_tm))
{ $no_of_days=29 ;}
else
{$no_of_days=28;}
}
$month_full=date("F",$dt_and_tm);


#
# ******* HTML code goes from here
# ******* First row in HTML table displays month and year
# ******* Second row is allotted for week days
# ******* Table contains six more rows (total 42 table cells)
#
?>








#
# *** We need to start form week day and print total number of days

# *** in this month.For that we need to find out the last cell.
# *** While looping end current row and start new row for each 7 cells
#
$last_cell=$week_day+$no_of_days;
for($i=1;$i<=42;$i++)
{
if($i==$week_day){$day=1;}
if($i<$week_day || $i>=$last_cell)
{

echo "";
if($i%7==0){echo "\n";}
}
else
{

echo "";
$day++;
if($i%7==0) { echo "\n"; }

}
}
?>

$year" ; ?>
Sunface="Arial , Times New Roman " size=2 color="#ffffff">Monface="Arial , Times New Roman " size=2 color="#ffffff">Tueface="Arial , Times New Roman " size=2 color="#ffffff">Wedface="Arial , Times New Roman " size=2 color="#ffffff">Thuface="Arial , Times New Roman " size=2 color="#ffffff">FriSat
?
$day

Continue Reading | comments

Databases sample source codes

A couple of functions that convert an IP address into its color code
and not-color-code. Useful when viewing an apache log with a mysql result grouped by IP

/*this function converts $ipaddr into a color string*/
function IP2Color($ipaddr) {

$pieces=explode(".",$ipaddr);
$color="";

for($i=0;$i<3;$i++) {
if(($pieces[$i]>=0) && ($pieces[$i]<=255)) {
$color.=dechex($pieces[$i]);
}
}
$color=substr($color."000000",0,6);
return("#".strtoupper($color));
}

/*this function converts $ipaddr
to anti color string*/

function IP2NotColor($ipaddr) {

$pieces=explode(".",$ipaddr);
$color="";

for($i=0;$i<3;$i++) {
if(($pieces[$i]>=0) && ($pieces[$i]<=255)) {
$color.=dechex((128+$pieces[$i]) % 255);
}
}
$color=substr($color."000000",0,6);
return("#".strtoupper($color));
}

Example:

$IP=getenv("REMOTE_ADDR");
print "\n";
print " \n";
print "
color='".IP2NotColor($IP)."'>$IP
\n";
?>
Continue Reading | comments

Graphics sample source codes

2D Line Plot (fully working)


class plot2D {
var $img, $imgWidth, $imgHeight, $fontSize, $fontWidth, $fontHeight, $cBack, $acPlot, $maxCatLen, $aItems, $maxVal, $numItems, $maxNumItems, $maxLinesDesc, $numberY, $cBlack, $cGrid;
var $graphX, $graphY, $graphWidth, $graphHeight;
var $titleString, $titleFontSize, $cTitle, $titleWidth, $titleHeight;
var $xDesc, $yDesc, $xDescLength, $yDescLength;
function plot2D($width=640, $height=480, $fontSize=2, $red=0xFF, $green=0xFF, $blue=0xFF) {
$this->img = imageCreate($width, $height);
$this->imgWidth = $width-10;
$this->imgHeight = $height;
$this->cBack = imageColorAllocate($this->img, $red, $green, $blue);
$this->cBlack = imageColorAllocate($this->img, 0, 0, 0);
$this->cNavy = imageColorAllocate($this->img, 0x00, 0x00, 0x80);
$this->fontSize = $fontSize;
$this->fontWidth = imageFontWidth($fontSize);
$this->fontHeight = imageFontHeight($fontSize);
$this->graphX = 0;
$this->graphY = 0;
$this->graphWidth = $this->imgWidth;
$this->graphHeight = $this->imgHeight;
$this->setGrid();
}

function setTitle($title, $fontSize=3, $red=0x00, $green=0x00, $blue=0x00) {
$this->titleString = $title;
$this->titleFontSize = $fontSize;
$this->cTitle = imageColorAllocate($this->img, $red, $green, $blue);
$this->titleWidth = imageFontWidth($fontSize) * strLen($title);
$this->titleHeight = imageFontHeight($fontSize);
$this->graphY = $this->graphY + ($this->titleHeight + 2);
$this->graphHeight = $this->graphHeight - ($this->titleHeight + 2);
}

function setDescription($x, $y="") {
if ($x) {
$this->xDesc = $x;
$this->xDescLength = $this->fontWidth * strLen($x);
$this->graphHeight = $this->graphHeight - ($this->fontHeight + 2);
}

if ($y) {
$this->yDesc = $y;
$this->yDescLength = $this->fontWidth * strLen($y);
$this->graphX = $this->graphX + ($this->fontHeight + 2);
$this->graphWidth = $this->graphWidth - ($this->fontHeight + 2);
}
}

function setGrid($number=5, $red=0xCC, $green=0xCC, $blue=0xCC) { //Horizontal grid
$this->cGrid = imageColorAllocate($this->img, $red, $green, $blue);
$this->numberY = $number;
}

function addCategory($description, $red, $green, $blue) {
$this->acPlot[$description] = imageColorAllocate($this->img, $red, $green, $blue);
if (strLen($description) > $this->maxCatLen)
$this->maxCatLen = strLen($description);
}

function categoryExists($description) {
if (isSet($this->acPlot[$description])) {
return true;
} else {
return false;
}
}

function addItem($category, $description, $value) {
$this->aItems[$category][$description] = $value;
$this->checkItem($category, $description, $this->aItems[$category][$description]);
}

function incrementItem($category, $description, $value) {
if (!isSet($this->aItems[$category][$description]))
$this->addItem($category, $description, $value);
$this->aItems[$category][$description] = $this->aItems[$category][$description] + $value;
$this->checkItem($category, $description, $this->aItems[$category][$description]);
}

function checkItem($category, $description, $value) {
if ($value > $this->maxVal)
$this->maxVal = $value;
$this->numItems[$category]++;
if ($this->numItems[$category] > $this->maxNumItems)
$this->maxNumItems = $this->numItems[$category];
if (sizeOf(explode("\n", $description)) > $this->maxLinesDesc)
$this->maxLinesDesc = sizeOf(explode("\n", $description));
}

function destroy() {
imageDestroy($this->img);
}

function printGraph($filename = 0) {
$this->graphHeight = $this->graphHeight - (($this->maxLinesDesc + 1) * ($this->fontHeight + 2)); //Adjust for bottom values
$this->graphX = $this->graphX + ($this->fontWidth * strLen($this->maxVal) + 2); //Adjust left margin for values
$this->graphWidth = $this->graphWidth - ($this->fontWidth * strLen($this->maxVal) + 2) - (($this->maxCatLen * $this->fontWidth) + 17) - (strLen($this->maxVal) * $this->fontWidth); //+17 = Adjust right margin for category descriptions
imageRectangle($this->img, $this->graphX, $this->graphY, $this->graphX + $this->graphWidth, $this->graphY + $this->graphHeight, $this->cBlack); //Box
if ($this->titleString)
imageString($this->img, $this->titleFontSize, $this->graphX + ($this->graphWidth / 2) - ($this->titleWidth / 2), 0, $this->titleString, $this->cTitle);
if ($this->xDesc)
imageString($this->img, $this->fontSize, $this->graphX + ($this->graphWidth / 2) - ($this->xDescLength / 2), $this->graphY + $this->graphHeight + (($this->maxLinesDesc + 1) * ($this->fontHeight + 2)), $this->xDesc, $this->cBlack);
if ($this->yDesc)
imageStringUp($this->img, $this->fontSize, 0, ($this->graphY + ($this->graphHeight / 2)) + ($this->xDescLength / 2), $this->yDesc, $this->cBlack);

for ($i = 0; $i <= $this->numberY; $i++) { //Grid
$yPos = $this->graphY + $i * ($this->graphHeight / ($this->numberY + 1));
if ($i)
imageLine($this->img, $this->graphX+1, $yPos, $this->graphX + $this->graphWidth - 1, $yPos, $this->cGrid);
$yVal = floor($this->maxVal - (($this->maxVal / ($this->numberY + 1)) * $i) + .5);
imageString($this->img, $this->fontSize, $this->graphX - 3 - ($this->fontWidth * strLen($yVal)), $yPos - ($this->fontHeight / 2), $yVal, $this->cNavy);
}

imageString($this->img, $this->fontSize, $this->graphX - 3 - $this->fontWidth, $this->graphY + $this->graphHeight - ($this->fontHeight / 2), "0", $this->cNavy);

$c = 0;
while (list($cDesc, $cColor) = each($this->acPlot)) { //Loop through categories
$s=0;
while (list($sKey, $sVal) = each($this->aItems[$cDesc])) { //Loop through items
$sum[$cDesc] += $sVal; //Sum up values for each category
$xPos = ($this->graphX + 4) + ((($this->graphWidth - 10) / ($this->maxNumItems - 1)) * $s);
$yPos = $this->graphY + ($this->graphHeight - floor((($sVal / $this->maxVal) * $this->graphHeight) + .5));
imageRectangle($this->img, $xPos - 2, $yPos - 2, $xPos + 2, $yPos + 2, $cColor);
if ($s)
imageLine($this->img, $prevX, $prevY, $xPos, $yPos, $cColor);

$aValues = explode("\n", $sKey);
for ($i = 0; $i < sizeOf($aValues); $i++) {
imageString($this->img, $this->fontSize, $xPos - ((strLen($aValues[$i]) * $this->fontWidth) / 2), $this->graphY + $this->graphHeight + 2 + ($i * ($this->fontHeight + 2)), $aValues[$i], $this->cNavy); //Bottom values
}
$prevX = $xPos;
$prevY = $yPos;
$s++;
}
$boxX = $this->graphX + $this->graphWidth + 5;
$boxY = $this->graphY + 10 + ($c * 15);
imageFilledRectangle($this->img, $boxX, $boxY, $boxX + 10, $boxY + 10, $cColor);
imageRectangle($this->img, $boxX, $boxY, $boxX + 10, $boxY + 10, $this->cBlack);
imageString($this->img, $this->fontSize, $boxX + 14, ($boxY + 5) - ($this->fontHeight / 2), $cDesc."=".$sum[$cDesc], $cColor);
$c++;
}
if ($filename) {
imagePNG($this->img, "$filename.png");
} else {
imagePNG($this->img);
}
}
}


//Example -- comment this out if you want to use the class on other pages.
header ("Content-type: image/png"); #Line added to ensure image displays correctly in browser

$plot = new plot2D();
$plot->setTitle("spending habits");
$plot->setDescription("Days of the week", "Dollars spent");
$plot->setGrid();
$plot->addCategory("Food", 0xCC, 0x00, 0x00);
$plot->addItem("Food", "sun\n12/1", 152);
$plot->addItem("Food", "mon\n12/2", 76);
$plot->addItem("Food", "tues\n12/3", 81);
$plot->addCategory("Candy", 0x00, 0xCC, 0x00);
$plot->addItem("Candy", "sun\n12/1", 51);
$plot->addItem("Candy", "mon\n12/2", 127);
$plot->addItem("Candy", "tues\n12/3", 45);
$plot->printGraph();
$plot->destroy();
?>
Continue Reading | comments

File Upload Script

if ( isset( $_FILES['fupload'] ) ) {

print "name: ". $_FILES['fupload']['name'] ."
";
print "size: ". $_FILES['fupload']['size'] ." bytes
";
print "temp name: ".$_FILES['fupload']['tmp_name'] ."
";
print "type: ". $_FILES['fupload']['type'] ."
";
print "error: ". $_FILES['fupload']['error'] ."
";

if ( $_FILES['fupload']['type'] == "image/gif" ) {

$source = $_FILES['fupload']['tmp_name'];
$target = "upload/".$_FILES['fupload']['name'];
move_uploaded_file( $source, $target );// or die ("Couldn't copy");
$size = getImageSize( $target );

$imgstr = "

$imgstr .= "src=\"$target\" alt=\"uploaded image\" />

";

print $imgstr;
}
}
?>
Continue Reading | comments

Student & Libary database using file& Swing

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;

import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class SampleDesktop13 extends JFrame implements ActionListener,ListSelectionListener
{
public JDesktopPane desk;
//JTabbedPane fpane = new JTabbedPane(SwingConstants.TOP);
Properties ht = new Properties();
Properties ht1 = new Properties();
String name,fname,number,add,tele,qua,sums,email;
String newSelection;
JMenuBar mb;
JMenu menu,menu1,menu2;
JMenuItem sadd,exit,lrecord,about;
JInternalFrame hide=new JInternalFrame();
int document = 1,tabIndex=0;
JTextField[] nameField;
JList list;
DefaultListModel listModel= new DefaultListModel();
JPanel pix22 = new JPanel();


int wcoboxchange=0;
int count1=0;
JList list1;
DefaultListModel listModel1= new DefaultListModel();
JPanel pix12 = new JPanel();

GregorianCalendar gcal=new GregorianCalendar();
String idate,doi,dor;
String rdate;
int id,im,iy,id1,im1,iy1;
int listboxno;

JRadioButton allButton;
JRadioButton javaButton;
JRadioButton cButton;
JRadioButton vbButton;
JLabel stb =new JLabel("The Student Holds This Books..");

int count;
String[] isb;

ArrayList alist=new ArrayList();

String bname,isbn,booktype,author,edition,booksum;

JPanel p=new JPanel();




public SampleDesktop13(String title){

super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);

desk = new JDesktopPane();
setContentPane(desk);
mb = new JMenuBar();
menu = new JMenu("Student DataBase");
menu1 = new JMenu("Libary");
menu2 = new JMenu("Help");
setJMenuBar(menuBar());
mb.add(menu);
mb.add(menu1);
mb.add(menu2);

}

private JMenuBar menuBar(){
sadd=new JMenuItem(" Student Record");
sadd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
sadd.addActionListener(this);
menu.add(sadd);
exit=new JMenuItem(" Exit");
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
exit.addActionListener(this);
menu.add(exit);

lrecord=new JMenuItem(" Libary Records");
lrecord.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
lrecord.addActionListener(this);
menu1.add(lrecord);

about=new JMenuItem(" About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
about.addActionListener(this);
menu2.add(about);

return mb;
}


public void actionPerformed(ActionEvent e){
if ((e.getSource()==sadd))
hide=newFile();
if ((e.getSource()==lrecord))
hide=lrecord1();
if ((e.getSource()==about))

JOptionPane.showMessageDialog( desk,"This is Created By Prosun");
if ((e.getSource()==exit))
System.exit(0);

if ("Cancel".equals(e.getActionCommand())){

hide.dispose();}

if ("OK".equals(e.getActionCommand())){

save();
JOptionPane.showMessageDialog( hide,"One Record saved");
hide.dispose();


}
if ("Update".equals(e.getActionCommand())){
if(wcoboxchange==0){
JOptionPane.showMessageDialog( hide,"Plz select from Combo");
}else{
Update();
JOptionPane.showMessageDialog( hide,"One Record Updated");
hide.dispose();
wcoboxchange=0;}
}
if ("Delete".equals(e.getActionCommand())){
if(wcoboxchange==0){
JOptionPane.showMessageDialog( hide,"Plz select from Combo");
}else{
Delete();
JOptionPane.showMessageDialog( hide,"One Record Deleted");
hide.dispose();
wcoboxchange=0;}}
if ("Finished".equals(e.getActionCommand())){
JOptionPane.showMessageDialog( hide,"One Record Showed");

hide.dispose();}
if ("Issue".equals(e.getActionCommand())){
if(nameField[2].getText().length()<1||nameField[1].getText().length()<1)
{
JOptionPane.showMessageDialog( hide,"PLz Give value for All Fields");
if(nameField[2].getText().length()<1){
nameField[2].requestFocus();}
else{nameField[1].requestFocus();}
}
else{
Issue();
hide.dispose();}
}
if ("Return".equals(e.getActionCommand())){
if(nameField[1].getText().length()<1){
JOptionPane.showMessageDialog( hide,"PLz Give value for All Fields");
nameField[1].requestFocus();
}else{
Returnbook();
hide.dispose();}
}
if ("Add".equals(e.getActionCommand())){
if(nameField[0].getText().length()<1||nameField[1].getText().length()<1)
{
JOptionPane.showMessageDialog( hide,"PLz Give value for All Fields");
if(nameField[0].getText().length()<1){
nameField[0].requestFocus();}
else{nameField[1].requestFocus();}
}
else{
Addbook();
JOptionPane.showMessageDialog( hide,"One Book Added To Libary");
hide.dispose();}}

if ("Delete Book".equals(e.getActionCommand())){
if(nameField[0].getText().length()<1){
JOptionPane.showMessageDialog( hide,"PLz Give value for All Fields");
nameField[0].requestFocus();
}else{
Deletebook();
JOptionPane.showMessageDialog( hide,"One Book Deleted From Libary");
hide.dispose();}}


if (e.getSource() == allButton){
//for all books
nameField[2].setText("");
changelist("allbooks.txt");


}
if (e.getSource() == javaButton){
//for java books
nameField[2].setText("");
changelist("javabooks.txt");

}
if (e.getSource() == cButton){
//for c books
nameField[2].setText("");
changelist("cbooks.txt");


}

if (e.getSource() == vbButton){
//for vb books
nameField[2].setText("");
changelist("vbbooks.txt");
}


}



//list listeners

public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {

if (list.getSelectedIndex() == -1) {
}
else{
if(listboxno==0){
String sd=(String)alist.get(list.getSelectedIndex());

nameField[2].setEditable(true);
nameField[2].setText(sd);
nameField[2].setEditable(false);}
else{

////////////////////////////////////////////

int n=0;
fileopen("issuedbook.txt");


String sums1 = (String) ht.get(newSelection);

String bdetails1="";

StringTokenizer st = new StringTokenizer(sums1,"#");
while(st.hasMoreTokens())
{
n++;
nameField[n].setEditable(true);

nameField[n].setText(st.nextToken());
nameField[n].setEditable(false);


}

///////////////////////////


nameField[4].setEditable(true);
nameField[4].setText(idate);

nameField[4].setEditable(false);
}
}
}
}



//list listner upto here


private void changelist(String s){
int n=0;



for( int i=0; i<count; i++ )
listModel.removeElementAt(0);

count=0; /////////////////////////////////////////////////////////

alist.clear();
addtoarray(s); if(!alist.isEmpty()){
for (Iterator iter = alist.iterator(); iter.hasNext();) {
fileopen("books.txt");


String sums = (String) ht.get((String)(iter.next()));

String bdetails="";

StringTokenizer st = new StringTokenizer(sums,"#");
while(st.hasMoreTokens())
{
bdetails=bdetails+st.nextToken()+" ";
}

listModel.addElement(bdetails);
count++;
}}
else{
listModel.addElement(alist);}
}

//aadd to arraay list

private void addtoarray(String s){
count=0;

try
{
DataInputStream readFile = new DataInputStream(new FileInputStream(s));
String rec = readFile.readLine();


while(rec != null)
{
StringTokenizer st = new StringTokenizer(rec,"#");
while(st.hasMoreTokens())
{

alist.add(st.nextToken());


rec = readFile.readLine(); //Random Access File
}
readFile.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}



}

//upto here arraylist




// trying libary Record

private JInternalFrame lrecord1(){
final JInternalFrame f1 = new JInternalFrame ("Test",false,true,false,true);
int width=Toolkit.getDefaultToolkit().getScreenSize().width;
int height=Toolkit.getDefaultToolkit().getScreenSize().height;
f1.setBounds( 0, 0, width-10, height - 80 );
f1.setTitle("All Fields Relating Books...");
//setDefaultCloseOperation(DISPOSE_ON_CLOSE );

//alist.clear();
//addtoarray("allbooks.txt");

final JTabbedPane fpane = new JTabbedPane(SwingConstants.TOP);

final JPanel pix1 = new JPanel();
final JPanel pix11 = new JPanel();
//final JPanel pix12 = new JPanel();

final JPanel pix2 = new JPanel();
final JPanel pix21 = new JPanel();
//final JPanel pix22 = new JPanel();
//final JLabel stb =new JLabel("The Student Holds This Books..");

final JPanel pix3 = new JPanel();
final JPanel pix4 = new JPanel();
getContentPane().setLayout(new SpringLayout());
fpane.addTab("Issue ",pix1);
fpane.addTab("Return ",pix2);
fpane.addTab("Add ",pix3);
fpane.addTab("Delete ",pix4);
fpane.setSelectedIndex(0);


final String[] labelStrings = {
"Name : ",
"Roll No : ","ISBN No :",
"DOI : ","DOR :"

};

final String[] labelStrings1 = {
"Name : ",
"ISBN NO : ",
"DOI : ","ADOR:","DOR :"

};

final String[] labelStrings2 = {
"Book Name : ",
"ISBN NO : ","Book Type :",
"Author : ","Edition :"

};


final String[] labelStrings3 = {

"ISBN NO : "


};


fpane.getModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
SingleSelectionModel model = (SingleSelectionModel) e.getSource();
if(model.getSelectedIndex() == fpane.getTabCount()-1) {
tabIndex=4;
pix4.removeAll();

f1.setSize(300,150);

pix4.setLayout(new BoxLayout(pix4,BoxLayout.PAGE_AXIS));

pix4.add(createEntryFields(labelStrings3));
pix4.add(createButtons("Delete Book","Cancel"));


}

if(model.getSelectedIndex() == fpane.getTabCount()-2) {

pix3.removeAll();

f1.setSize(300,250);

tabIndex=3;
pix3.setLayout(new BoxLayout(pix3,BoxLayout.PAGE_AXIS));

pix3.add(createEntryFields(labelStrings2));
pix3.add(createButtons("Add","Cancel"));


}
if(model.getSelectedIndex() == fpane.getTabCount()-3) {

pix2.removeAll();
pix21.removeAll();
pix22.removeAll();

pix2.setLayout(new GridLayout());


pix22.setLayout(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx = 0.5;
c1.gridx = 0;
c1.gridy = 0;


pix22.add(stb,c1);

c1.ipady = 30; //make this component tall
c1.weightx = 0.0;
c1.gridwidth = 3;
c1.gridx = 0;
c1.gridy = 1;


stb.setVisible(false);
//listModel.clear();
//alist.clear();
pix22.add(drawlist(),c1);
pix22.setVisible(false);
listboxno=1;



pix21.setLayout(new BoxLayout(pix21,BoxLayout.PAGE_AXIS));
pix21.add(createcombo(1));
pix21.add(createEntryFields(labelStrings1));
pix21.add(createButtons("Return","Cancel"));

pix2.add(pix21);
pix2.add(pix22);
f1.pack();
}
if(model.getSelectedIndex() == fpane.getTabCount()-4) {

tabIndex=1;
pix1.removeAll();
pix11.removeAll();
pix12.removeAll();

pix1.setLayout(new GridLayout());

pix11.setLayout(new BoxLayout(pix11,BoxLayout.PAGE_AXIS));
pix11.add(createEntryFields(labelStrings));
pix11.add(createButtons("Issue","Cancel"));

pix12.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;

c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;


pix12.add(addradiobutton(),c);


c.ipady = 30; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;

//listModel.clear();
pix12.add(drawlist(),c);
changelist("allbooks.txt");
listboxno=0;

nameField[3].setText(idate);
nameField[3].setEditable(false);

returndate();

pix1.add(pix11);
pix1.add(pix12);
f1.pack();



}
}
}
);

pix1.removeAll();
pix11.removeAll();
pix12.removeAll();


pix1.setLayout(new GridLayout());

pix11.setLayout(new BoxLayout(pix11,BoxLayout.PAGE_AXIS));
pix11.add(createEntryFields(labelStrings));
pix11.add(createButtons("Issue","Cancel"));

pix12.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;

c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;


pix12.add(addradiobutton(),c);


c.ipady = 30; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;


//listModel.clear();
pix12.add(drawlist(),c);
changelist("allbooks.txt");
listboxno=0;
id= gcal.get(Calendar.DATE);
im=(int)gcal.get(Calendar.MONTH)+1;
iy=gcal.get(Calendar.YEAR);


idate=id+"/"+im+"/"+iy;

nameField[3].setText(idate);
nameField[3].setEditable(false);
returndate();

pix1.add(pix11);
pix1.add(pix12);
f1.pack();




f1.getContentPane().add(fpane);

JDesktopPane desktop = new JDesktopPane();
desktop.add(f1);

desk.add(f1);

f1.setVisible(true);
//f1.pack();
return f1;
}

//libary record upto here

//Issueing a book

private void Issue(){
String isbn1=nameField[2].getText();



fileopen("srecord.txt");

try{
number=nameField[1].getText();
String ert=(String)ht.get(number);
ht.clear();
insertroll(number,"irollno.txt");

if(ert.length()>1){

doi=nameField[3].getText();
dor=nameField[4].getText();

String tmp=isbn1+"#"+doi+"#"+dor;
ht1.clear();
fileopen1("issuedbook.txt");
ht1.put(number,tmp);
writetofile1("issuedbook.txt");
JOptionPane.showMessageDialog( hide,"One Book Issued");

}
}catch(NullPointerException e){
JOptionPane.showMessageDialog( hide,"Sorry u R Not A Student");}
}


protected void writetofile1(String s){
try{

File f=new File(s);
f.delete();
FileOutputStream fout = new FileOutputStream(s,true) ;
ht1.store(fout,"Prosun~s creation");

fout.close();
}catch(IOException e){}

}


//book issue upto here

//return a book

private void Returnbook(){
comparedate();

fileopen("issuedbook.txt");
deletearecord("issuedbook.txt",newSelection);
deletefromsuppotedfile("irollno.txt",newSelection);


JOptionPane.showMessageDialog( hide,"One Book Returned");
ht.clear();
}

//function for deleting a record from file

private void deletearecord(String fn,String key){

File f=new File(fn);
f.delete();
try{
FileOutputStream fout = new FileOutputStream(fn,true);
ht.remove(key);
ht.store(fout,"Prosun~s creation");
fout.close();
}catch(IOException e){}

ht.clear();

}

//function for deleting a record from file upto here

//book return upto here

//delete book from libary
private void Deletebook(){
String sd=nameField[0].getText();
fileopen("books.txt");
deletearecord("books.txt",sd);
deletefromsuppotedfile("cbooks.txt",sd);
deletefromsuppotedfile("javabooks.txt",sd);
deletefromsuppotedfile("vbbooks.txt",sd);
deletefromsuppotedfile("allbooks.txt",sd);

}

//delete book from libary upto here


/////////////////Delete Book no from Supporting files////////////////

private void deletefromsuppotedfile(String fn,String key){

try
{
DataInputStream readFile = new DataInputStream(new FileInputStream(fn));
String rec = readFile.readLine();
String rolllist=null;

DataOutputStream writeFile1 = new DataOutputStream(new FileOutputStream("temp1.txt",true));




while(rec != null)
{
StringTokenizer st = new StringTokenizer(rec,"#");
while(st.hasMoreTokens())
{

String n=st.nextToken();
rec = readFile.readLine();
if(!n.equals(key)){
//writimg to a tempfile
writeFile1.writeBytes(n+"#");
}

}
readFile.close();
writeFile1.close();
}


filecopy("temp1.txt",fn);



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


}
////////////////////////upto here///////////////////////////////////////



private void comparedate(){
String sr=nameField[3].getText();
int rd,rm,ry;
StringTokenizer st = new StringTokenizer(sr,"/");
rd=Integer.parseInt(st.nextToken());
rm=Integer.parseInt(st.nextToken());
ry=Integer.parseInt(st.nextToken());
if(iy>ry){
JOptionPane.showMessageDialog( hide,"You Must Give Fine For Delay");
}else{
if(im>rm){
JOptionPane.showMessageDialog( hide,"You Must Give Fine For Delay");}
else{
if(id>rd)
JOptionPane.showMessageDialog( hide,"You Must Give Fine For Delay");}
}
}

private void returndate(){

im1=im;
iy1=iy;
id1=id+15;

if(im1==1||im1==3||im1==5||im1==7||im1==8||im1==10||im1==12){
if(id1>31){
im1=im1+1;
id1=id1-31;
if(im1>12){
im1=im1-12;
iy1=iy1+1;
}}}


if(im1==4||im1==6||im1==9||im1==11){
if(id1>30){
im1=im1+1;
id1=id1-30;
if(im1>12){
im1=im1-12;
iy1=iy1+1;}
}}


if(im1==2){
if(id1>28){
im1=im1+1;
id1=id1-28;
if(im1>12){
im1=im1-12;
iy1=iy1+1;
}}}

rdate = id1+"/"+im1+"/"+iy1;
nameField[4].setEditable(true);
nameField[4].setText(rdate);
nameField[4].setEditable(false);

}

private JPanel addradiobutton(){

JPanel pix12= new JPanel();
String allString= "All";
String javaString= "Java";
String cString= "C";
String vbString= "Vb";




allButton = (JRadioButton) pix12.add(new JRadioButton(allString));
allButton.setActionCommand(allString);
allButton.setSelected(true);

javaButton =(JRadioButton) pix12.add( new JRadioButton(javaString));

javaButton.setActionCommand(javaString);

cButton =(JRadioButton) pix12.add( new JRadioButton(cString));

cButton.setActionCommand(cString);

vbButton =(JRadioButton) pix12.add( new JRadioButton(vbString));

vbButton.setActionCommand(vbString);



//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(allButton);
group.add(javaButton);
group.add(cButton);
group.add(vbButton);




//Register a listener for the radio buttons.
allButton.addActionListener(this);
javaButton.addActionListener(this);
cButton.addActionListener(this);
vbButton.addActionListener(this);



return pix12;


}

private JPanel drawlist() {




listModel.addElement("prosun");
count++;

//Create the list and put it in a scroll pane.

list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
list.setVisibleRowCount(5);
JScrollPane listScrollPane = new JScrollPane(list);


String name = listModel.getElementAt(
list.getSelectedIndex()).toString();

//Create a panel that uses BoxLayout.
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane,
BoxLayout.LINE_AXIS));

buttonPane.add(Box.createHorizontalStrut(5));
//buttonPane.add(new JSeparator(SwingConstants.HORIZONTAL));
buttonPane.add(Box.createHorizontalStrut(5));



buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

buttonPane.add(listScrollPane, BorderLayout.CENTER);




return buttonPane;
}





private void Addbook(){
fileopen("books.txt");
bname=nameField[0].getText();
isbn=nameField[1].getText();
booktype=nameField[2].getText();
author=nameField[3].getText();
edition=nameField[4].getText();

booksum=bname+"#"+author+"#"+edition;
ht.put(isbn,booksum);
writetofile("books.txt");


try{
DataOutputStream writeFile2 = new DataOutputStream(new FileOutputStream("allbooks.txt",true)); writeFile2.writeBytes(isbn+"#");
writeFile2.close();
}catch(IOException e){}




if(booktype.equals("c")){
try{
DataOutputStream writeFile1 = new DataOutputStream(new FileOutputStream("cbooks.txt",true)); writeFile1.writeBytes(isbn+"#");
writeFile1.close();
}catch(IOException e){}
}


if(booktype.equals("vb")){
try{
DataOutputStream writeFile1 = new DataOutputStream(new FileOutputStream("vbbooks.txt",true)); writeFile1.writeBytes(isbn+"#");
writeFile1.close();
}catch(IOException e){}
}

if(booktype.equals("java")){
try{
DataOutputStream writeFile1 = new DataOutputStream(new FileOutputStream("javabooks.txt",true)); writeFile1.writeBytes(isbn+"#");
writeFile1.close();
}catch(IOException e){}
}

}


private JInternalFrame newFile(){
final JInternalFrame f = new JInternalFrame ("Test",false,true,false,true);
int width=Toolkit.getDefaultToolkit().getScreenSize().width;
int height=Toolkit.getDefaultToolkit().getScreenSize().height;
f.setBounds( 0, 0, width-10, height - 80 );
f.setTitle("All Fields Regarding Students..");



final JTabbedPane fpane = new JTabbedPane(SwingConstants.TOP);


final JPanel pix1 = new JPanel();
final JPanel pix2 = new JPanel();
final JPanel pix3 = new JPanel();
final JPanel pix4 = new JPanel();


getContentPane().setLayout(new SpringLayout());

fpane.addTab("Add",pix1);
fpane.addTab("Update",pix2);
fpane.addTab("Search",pix3);
fpane.addTab("Delete",pix4);
fpane.setSelectedIndex(0);

final String[] labelStrings = {
"Name : ",
"Father Name: ","Roll No :",
"Address: ","Qualification :",
"E_Mail: ","Tele Ph :"
};

final String[] labelStrings1 = {
"Name : ",
"Father Name: ",
"Address: ","Qualification :",
"E_Mail: ","Tele Ph :"
};



fpane.getModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
SingleSelectionModel model = (SingleSelectionModel) e.getSource();
if(model.getSelectedIndex() == fpane.getTabCount()-1) {
tabIndex=4;
wcoboxchange=0;
pix4.removeAll();
pix4.setLayout(new BoxLayout(pix4,BoxLayout.PAGE_AXIS));
pix4.add(createcombo(0));
pix4.add(createEntryFields(labelStrings1));
pix4.add(createButtons("Delete","Cancel"));


}

if(model.getSelectedIndex() == fpane.getTabCount()-2) {

pix3.removeAll();
wcoboxchange=0;
pix3.setLayout(new BoxLayout(pix3,BoxLayout.PAGE_AXIS));
pix3.add(createcombo(0));
pix3.add(createEntryFields(labelStrings1));
pix3.add(createButtons("Finished","Cancel"));
tabIndex=3;
}
if(model.getSelectedIndex() == fpane.getTabCount()-3) {
wcoboxchange=0;
pix2.removeAll();
pix2.setLayout(new BoxLayout(pix2,BoxLayout.PAGE_AXIS));
pix2.add(createcombo(0));
pix2.add(createEntryFields(labelStrings1));
pix2.add(createButtons("Update","Cancel"));
tabIndex=2;

}
if(model.getSelectedIndex() == fpane.getTabCount()-4) {
wcoboxchange=0;
tabIndex=1;
pix1.removeAll();
pix1.setLayout(new BoxLayout(pix1,BoxLayout.PAGE_AXIS));

pix1.add(createEntryFields(labelStrings));
pix1.add(createButtons("OK","Cancel"));


}
}
}
);



pix1.setLayout(new BoxLayout(pix1,BoxLayout.PAGE_AXIS));

pix1.add(createEntryFields(labelStrings));
pix1.add(createButtons("OK","Cancel"));



f.getContentPane().add(fpane);

JDesktopPane desktop = new JDesktopPane();
desktop.add(f);

desk.add(f);
f.setLocation(100,75);
f.setVisible(true);
return f;
}


//trying from downloded code


public JFormattedTextField getTextField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DefaultEditor) {
return ((JSpinner.DefaultEditor)editor).getTextField();
} else {
System.err.println("Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn~t a descendant of DefaultEditor");
return null;
}
}

//downloded code ends heres

protected JComponent createEntryFields(String[] labelStrings) {
JPanel panel = new JPanel(new SpringLayout());

JLabel[] labels = new JLabel[labelStrings.length];
JComponent[] fields = new JComponent[labelStrings.length];
int fieldNum = 0;
nameField = new JTextField[labelStrings.length];



for(int p=0;p<labelStrings.length;p++){
nameField[p] = new JTextField(20);
nameField[p].setColumns(20);
fields[fieldNum++] = nameField[p];

nameField[p].setMaximumSize(nameField[p].getPreferredSize());}


//Associate label/field pairs, add everything,
//and lay it out.
for (int i = 0; i < labelStrings.length; i++) {
labels[i] = new JLabel(labelStrings[i],
JLabel.TRAILING);
labels[i].setLabelFor(fields[i]);
labels[i] .setMaximumSize(labels[i] .getPreferredSize());
panel.add(labels[i]);
panel.add(fields[i]);

//Add listeners to each field.
JTextField tf = null;
tf = (JTextField)fields[i];
tf.addActionListener(this);

//nameField1[i]=nameField[i];



}
makeCompactGrid(panel,
labelStrings.length, 2,
6, 6, //init x,y
7, 7);//xpad, ypad
return panel;
}


protected void fileopen(String s){
FileInputStream fin = null;
ht.clear();
try{
fin = new FileInputStream(s);
}catch(FileNotFoundException e){

//ignoring missing file
}

try {
if(fin != null){
ht.load(fin);
fin.close();
}
}catch(IOException e) {
System.out.println("Error reading file");
}
}

protected void fileopen1(String s){
FileInputStream fin = null;
try{
fin = new FileInputStream(s);
}catch(FileNotFoundException e){

//ignoring missing file
}

try {
if(fin != null){
ht1.load(fin);
fin.close();
}
}catch(IOException e) {
System.out.println("Error reading file");
}


}

protected void writetofile(String s){
try{

File f=new File(s);
f.delete();
FileOutputStream fout = new FileOutputStream(s,true) ;
ht.store(fout,"Prosun~s creation");

fout.close();
}catch(IOException e){}

}

private void save(){

fileopen("srecord.txt");


name=nameField[0].getText();

fname=nameField[1].getText();
number=nameField[2].getText();
add=nameField[3].getText();
qua=nameField[4].getText();
email=nameField[5].getText();
tele=nameField[6].getText();

insertroll(number,"roll.txt");

sums=name+"#"+fname+"#"+add+"#"+qua+"#"+email+"#"+tele;

ht.put(number,sums);



writetofile("srecord.txt");

}
//save upto here


private void Update(){

fileopen("srecord.txt");


name=nameField[0].getText();

fname=nameField[1].getText();
//number=nameField2[2].getText();
number=newSelection;
add=nameField[2].getText();
qua=nameField[3].getText();
email=nameField[4].getText();
tele=nameField[5].getText();

//insertroll(number);

sums=name+"#"+fname+"#"+add+"#"+qua+"#"+email+"#"+tele;

ht.put(number,sums);



writetofile("srecord.txt");

}

public void insertroll(String number,String fn)
{
try
{
DataOutputStream writeFile = new DataOutputStream(new FileOutputStream(fn,true));
String rec = number+"#";
writeFile.writeBytes(rec);


writeFile.close();
}
catch(Exception e)
{
//e.printStackTrace();
}
}




//trying to delete

private void Delete(){

fileopen("srecord.txt");



File f=new File("d:\prosun\SWING\srecord.txt");
f.delete();
try{
FileOutputStream fout = new FileOutputStream("srecord.txt",true);
ht.remove(newSelection);
ht.store(fout,"Prosun~s creation");
fout.close();
}catch(IOException e){}


deletefromsuppotedfile("roll.txt",newSelection);


}


//detete upto here

//file copy

private void filecopy(String a,String b){


int i;
FileInputStream fin;
FileOutputStream fout;


try{

try{
fin =new FileInputStream(a);
}catch(FileNotFoundException e){
System.out.println("FILE NOT FOUND");
return;}

try{
File f1=new File("d:\prosun\SWING\roll.txt");
f1.delete();

fout =new FileOutputStream(b);
}catch(FileNotFoundException e){
System.out.println("OUTPUT FILE NOT FOUND");
return;}
}

catch(ArrayIndexOutOfBoundsException e){
System.out.println("usage");
return;}

// read characters until EOF

try{

do{
i=fin.read();
if(i !=-1)
fout.write(i);
//System.out.print((char) i);
}
while(i!=-1);}
catch(IOException e){
System.out.println("file Error");
}
try{
fin.close();
fout.close();

File f2=new File("d:\prosun\SWING\temp1.txt");
f2.delete();
}catch(IOException e){}

}
//copy file upto here

protected JComponent createButtons(String s,String t) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));

JButton button = new JButton(s);
button.addActionListener(this);
button.setActionCommand(s);
panel.add(button);

button = new JButton(t);
button.addActionListener(this);
button.setActionCommand(t);
panel.add(button);

//Match the SpringLayout~s gap, subtracting 5 to make
//up for the default gap FlowLayout provides.
panel.setBorder(BorderFactory.createEmptyBorder(0, 0,
10, 10));
return panel;
}

/*//adding actionlistener to the buttons
public void actionPerformed(ActionEvent e) {
if ("clear".equals(e.getActionCommand())) {
System.out.exit(0);

}}*/
//upto here for buttons


protected JComponent createcombo(final int t) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
JLabel rol=new JLabel(" Roll No :");


JComboBox petList = new JComboBox();
DataInputStream readFile;
try
{
if(t==1){
readFile = new DataInputStream(new FileInputStream("irollno.txt"));}
else{
readFile = new DataInputStream(new FileInputStream("roll.txt"));}
String rec = readFile.readLine();


while(rec != null)
{
StringTokenizer st = new StringTokenizer(rec,"#");
while(st.hasMoreTokens())
{
//System.out.println(st.nextToken()+" ");
petList.addItem(st.nextToken());
rec = readFile.readLine(); //Random Access File
}
readFile.close();
}
}
catch(Exception e)
{
//e.printStackTrace();
}

//petList.setSelectedIndex(0);
petList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource() ;
newSelection = (String)cb.getSelectedItem();
if(t==1){
//count1=0;
reformat1(newSelection); }

if(t==0){
reformat(newSelection);
wcoboxchange=1;
}
}
});




panel.add("EAST",rol);
panel.add(petList);



//Match the SpringLayout~s gap, subtracting 5 to make
//up for the default gap FlowLayout provides.
panel.setBorder(BorderFactory.createEmptyBorder(0, 0,
1, 1));
return panel;
}




private void reformat1(String s){


stb.setVisible(true);
pix22.setVisible(true);
int n=0;



for( int i=0; i<count; i++ ) {
listModel.removeElementAt(0);
}
count=0;
fileopen("issuedbook.txt");
String sums1 = (String) ht.get(s);
String bdetails1="";
ht.clear();

fileopen("srecord.txt");
String sums2 = (String) ht.get(s);
ht.clear();
StringTokenizer st3 = new StringTokenizer(sums2,"#");
nameField[0].setText(st3.nextToken());

StringTokenizer st = new StringTokenizer(sums1,"#");
while(st.hasMoreTokens())
{
n++;
String em= st.nextToken();
//changing inside

if(n==1||n==4||n==7){

fileopen1("books.txt");
String rec1= (String) ht1.get(em);
//nameField[0].setText(em);

StringTokenizer st1 = new StringTokenizer(rec1,"#");
while(st1.hasMoreTokens()){
bdetails1=bdetails1+st1.nextToken()+" ";


}

listModel.addElement(bdetails1);
bdetails1="";
count++;

}else{
count1=count1;
st.nextToken();}
//changing innside upto here


}



}




//change

private void reformat(String s){
FileInputStream fin = null;

try{
fin = new FileInputStream("srecord.txt");
}catch(FileNotFoundException e){

//ignoring missing file
}

try {
if(fin != null){
ht.load(fin);
fin.close();
}
}catch(IOException e) {
System.out.println("Error reading file");
}

String sums = (String) ht.get(s);
int i=0;
StringTokenizer st = new StringTokenizer(sums,"#");
while(st.hasMoreTokens())
{
nameField[i].setText(st.nextToken());
i++;
}
//fin.close();
}

//change for compactgrid
public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}

//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}

//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}

//Set the parent~s size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}


//upto here compactgrid
//change cons
private static SpringLayout.Constraints getConstraintsForCell(
int row, int col,
Container parent,
int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}

//traints




public static void main(String args[]){
int width=Toolkit.getDefaultToolkit().getScreenSize().width;
int height=Toolkit.getDefaultToolkit().getScreenSize().height;
SampleDesktop13 td = new SampleDesktop13("Digital Libary System");
td.setSize(width,height-30);
td.setVisible(true);
}
}
Continue Reading | comments

Tic Tac Toe Game in java

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

class TicTacToe
{
public static void main(String s[])
{
UserInterface uf=new UserInterface();
uf.setSize(400,300);
uf.setLocation(120,90);
uf.setResizable(false);
uf.setVisible(true);
}
}


class UserInterface extends JFrame implements ActionListener
{
JMenuBar jmb;
JMenu jm1,jm3;
JMenuItem jmi1,jmi2,jmi4;

UserInterface()
{
this.setTitle("TicTacToe");
jmb=new JMenuBar();

jm1=new JMenu("File");
jmi1=new JMenuItem("New");
jmi2=new JMenuItem("Exit");

jm1.add(jmi1);
jm1.addSeparator();
jm1.add(jmi2);

jmi1.addActionListener(this);
jmi2.addActionListener(this);


jm3=new JMenu("Player");
jmi4=new JMenuItem("Choose Player");

jm3.add(jmi4);

jmi4.addActionListener(this);

jmb.add(jm1);
jmb.add(jm3);

setJMenuBar(jmb);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}




public void actionPerformed(ActionEvent e)
{

JMenuItem jmi=(JMenuItem)e.getSource();

if(jmi==jmi1)
{
UserInterface uf=new UserInterface();
uf.setSize(400,300);
uf.setLocation(120,90);
uf.setResizable(false);
uf.setVisible(true);
}

if(jmi==jmi2)
{
System.exit(0);
}


if(jmi==jmi4)
{
boolean flag=true;
String Pname=JOptionPane.showInputDialog("Enter Your Name..... ");
String Po=JOptionPane.showInputDialog("If u want to play as Leading player type ~1~ else type ~2~");
Pname=Pname.trim();
int p=Integer.parseInt(Po.trim());

this.setVisible(false);
Board b=new Board(Pname,p);
b.setSize(400,300);
b.setLocation(120,90);
b.setResizable(false);
b.setLayout(null);
b.setVisible(true);
}
}
}


class Board extends JFrame implements ActionListener
{
JMenuBar jmb;
JMenu jm1,jm2;
JMenuItem jmi1,jmi2,jmi3;
JButton jb[][]=new JButton[3][3];
int arr[][]=new int[3][3];
String Pname;
int Po,turn=1;
Board(String Pname,int Po)
{
this.Pname=Pname;
this.Po=Po;
//System.out.print(Pname);
//System.out.print(Po);

for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
arr[i][j]=2;

this.setTitle("TicTacToe");
jmb=new JMenuBar();

jm1=new JMenu("File");
jmi1=new JMenuItem("New");
jmi2=new JMenuItem("Exit");

jm1.add(jmi1);
jm1.addSeparator();
jm1.add(jmi2);

jmi1.addActionListener(this);
jmi2.addActionListener(this);

jm2=new JMenu("Edit");
jmi3=new JMenuItem("Undo");

jm2.add(jmi3);

jmi3.addActionListener(this);

jmb.add(jm1);
jmb.add(jm2);


setJMenuBar(jmb);

if(this.Po==1)
{
//System.out.println(Pname);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
jb[i][j]=new JButton("");

for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
jb[i][j].setBounds(0+i*130,0+j*80,130,80);
add(jb[i][j]);
jb[i][j].addActionListener(this);
}

}

if(this.Po==2)
{
//System.out.println(Pname);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
jb[i][j]=new JButton("");

for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
jb[i][j].setBounds(0+i*130,0+j*80,130,80);
add(jb[i][j]);
jb[i][j].addActionListener(this);
}
OnClickT();

}



addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

}

public void actionPerformed(ActionEvent e)
{

JComponent jc=(JComponent)e.getSource();


for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(jc==jb[i][j])
{
if(Po==1)
{

jb[i][j].setText("X");
arr[i][j]=3;
if(turn<9)
{
int k=0,l=0;
turn++;


if(arr[0][0]*arr[2][2]*arr[1][1]==27)
{
/*Final f=new Final(this);
f.setSize(400,300);
f.setLocation(120,90);
f.setResizable(false);
f.setLayout(null);
f.setVisible(true);*/

this.setVisible(false);
new win(~P~,Pname);
}
else
{
if(arr[2][0]*arr[1][1]*arr[0][2]==27)
{
/*Final f=new Final(this);
f.setSize(400,300);
f.setLocation(120,90);
f.setResizable(false);
f.setLayout(null);
f.setVisible(true);*/

this.setVisible(false);
new win(~P~,Pname);
}
else
{
while(l==0)
{
for(k=0;k<3;k++)
{

if(arr[k][0]*arr[k][1]*arr[k][2]==27)
{
l++;
/*Final f=new Final(this);
f.setSize(400,300);
f.setLocation(120,90);
f.setResizable(false);
f.setLayout(null);
f.setVisible(true);*/

this.setVisible(false);
new win(~P~,Pname);
}
else
{
if(arr[0][k]*arr[1][k]*arr[2][k]==27)
{
l++;
/*Final f=new Final(this);
f.setSize(400,300);
f.setLocation(120,90);
f.setResizable(false);
f.setLayout(null);
f.setVisible(true);*/

this.setVisible(false);
new win(~P~,Pname);
}


}
System.out.println("k=="+k);
}
l++;
}
if(l!=2)
{
System.out.println("");
System.out.println("l!=2");
OnClickL();
}
}
}




//OnClickL();
}
else
{
this.setVisible(false);
new win(~D~,"Dwawn");
}
}
if(Po==2)
{
jb[i][j].setText("O");
arr[i][j]=5;
turn++;
int k=0,l=0;


if(arr[0][0]*arr[2][2]*arr[1][1]==125)
{
this.setVisible(false);
new win(~P~,Pname);
}
else
{
if(arr[2][0]*arr[1][1]*arr[0][2]==125)
{
this.setVisible(false);
new win(~P~,Pname);
}
else
{
while(l==0)
{
for(k=0;k<3;k++)
{
if(arr[k][0]*arr[k][1]*arr[k][2]==125)
{
l++;
this.setVisible(false);
new win(~P~,Pname);
}
else
{
if(arr[0][k]*arr[1][k]*arr[2][k]==125)
{
l++;
this.setVisible(false);
new win(~P~,Pname);
}
}
System.out.println("k=="+k);
}
l++;
}
if(l!=2)
{
System.out.println("");
System.out.println("l!=2");
OnClickT();
}
}
}
}
}
}

if(jc==(JComponent)jmi1)
{
UserInterface uf=new UserInterface();
uf.setSize(400,300);
uf.setLocation(120,90);
uf.setResizable(false);
uf.setVisible(true);
}

if(jc==(JComponent)jmi2)
{
System.exit(0);
}

if(jc==(JComponent)jmi3)
{

}
}

void OnClickT()
{
if(turn==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(turn==3)
{
if(arr[2][2]!=2)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
else
{
arr[2][2]=3;
jb[2][2].setText("X");
}
}

if(turn==5)
{
int n=posswin(~X~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(n==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}

if(n==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(n==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}

if(n==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(n==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(n==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(n==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
this.setVisible(false);
new win(~C~,Pname);
}
else
{
int m=posswin(~O~);
if(m!=0)
{
if(m==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(m==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}

if(m==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(m==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}

if(m==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(m==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(m==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(m==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
}
else
{
if(arr[0][2]==2)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
else
{
arr[2][0]=3;
jb[2][0].setText("X");
}
}
}
}

if(turn==7)
{
int n=posswin(~X~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(n==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}

if(n==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(n==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}

if(n==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(n==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(n==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(n==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
this.setVisible(false);
new win(~C~,Pname);
}
else
{
int m=posswin(~O~);
if(m!=0)
{
if(m==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(m==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}

if(m==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(m==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}

if(m==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(m==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(m==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(m==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
}
else
{
int cou=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(cou<1 && arr[i][j]==2)
{
arr[i][j]=3;
jb[i][j].setText("X");
}
}
}
}

}

if(turn==9)
{
int n=posswin(~X~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}

if(n==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}

if(n==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(n==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}
if(n==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(n==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(n==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(n==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
this.setVisible(false);
new win(~C~,Pname);
}
else
{
int m=posswin(~O~);
if(m!=0)
{
if(m==1)
{
arr[0][0]=3;
jb[0][0].setText("X");
}
if(m==2)
{
arr[1][0]=3;
jb[1][0].setText("X");
}
if(m==3)
{
arr[2][0]=3;
jb[2][0].setText("X");
}
if(m==4)
{
arr[0][1]=3;
jb[0][1].setText("X");
}
if(m==6)
{
arr[2][1]=3;
jb[2][1].setText("X");
}
if(m==7)
{
arr[0][2]=3;
jb[0][2].setText("X");
}
if(m==8)
{
arr[1][2]=3;
jb[1][2].setText("X");
}
if(m==9)
{
arr[2][2]=3;
jb[2][2].setText("X");
}
}
else
{
int cou=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(cou<1 && arr[i][j]==2)
{
arr[i][j]=3;
jb[i][j].setText("X");
}
}
}
this.setVisible(false);
new win(~D~,"Drawn");
}
}
}
turn++;
}

void OnClickL()
{
if(turn==2)
{
if(arr[1][1]!=2)
{
arr[0][0]=5;
jb[0][0].setText("O");
}
else
{
arr[1][1]=5;
jb[1][1].setText("O");
}
}

if(turn==4)
{
int n=posswin(~X~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=5;
jb[0][0].setText("O");
}

if(n==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}

if(n==3)
{
arr[2][0]=5;
jb[2][0].setText("O");
}
if(n==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(n==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(n==7)
{
arr[0][2]=5;
jb[0][2].setText("O");
}
if(n==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(n==9)
{
arr[2][2]=5;
jb[2][2].setText("O");
}
}
else
{
System.out.println("test");
int m=make2();
System.out.println(m);
if(m==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}
if(m==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(m==5)
{
arr[1][1]=5;
jb[1][1].setText("O");
}

if(m==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(m==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(m==99)
{
int cou=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(arr[i][j]==2 && cou<1)
{
arr[i][j]=5;
jb[i][j].setText("O");
cou++;
}

}
}


}
}

if(turn==6)
{
int n=posswin(~O~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=5;
jb[0][0].setText("O");
}

if(n==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}

if(n==3)
{
arr[2][0]=5;
jb[2][0].setText("O");
}
if(n==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(n==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(n==7)
{
arr[0][2]=5;
jb[0][2].setText("O");
}
if(n==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(n==9)
{
arr[2][2]=5;
jb[2][2].setText("O");
}
this.setVisible(false);
new win(~C~,Pname);

}
else
{
int n1=posswin(~X~);
if(n1!=0)
{
if(n1==1)
{
arr[0][0]=5;
jb[0][0].setText("O");
}

if(n1==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}

if(n1==3)
{
arr[2][0]=5;
jb[2][0].setText("O");
}
if(n1==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(n1==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(n1==7)
{
arr[0][2]=5;
jb[0][2].setText("O");
}
if(n1==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(n1==9)
{
arr[2][2]=5;
jb[2][2].setText("O");
}
}
else
{
int m=make2();
if(m==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}
if(m==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(m==5)
{
arr[1][1]=5;
jb[1][1].setText("O");
}

if(m==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(m==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(m==0)
{
int count=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(count==0)
{
if(arr[i][j]==2)
{
arr[i][j]=5;
jb[i][j].setText("O");
count++;
}
}
}
}
}
}
}
}

if(turn==8)
{
int n=posswin(~O~);
if(n!=0)
{
if(n==1)
{
arr[0][0]=5;
jb[0][0].setText("O");
}

if(n==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}

if(n==3)
{
arr[2][0]=5;
jb[2][0].setText("O");
}
if(n==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(n==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(n==7)
{
arr[0][2]=5;
jb[0][2].setText("O");
}
if(n==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(n==9)
{
arr[2][2]=5;
jb[2][2].setText("O");
}

this.setVisible(false);
new win(~C~,Pname);

}
else
{
int n1=posswin(~X~);
if(n1!=0)
{
if(n1==1)
{
arr[0][0]=5;
jb[0][0].setText("O");
}

if(n1==2)
{
arr[1][0]=5;
jb[1][0].setText("O");
}

if(n1==3)
{
arr[2][0]=5;
jb[2][0].setText("O");
}
if(n1==4)
{
arr[0][1]=5;
jb[0][1].setText("O");
}

if(n1==6)
{
arr[2][1]=5;
jb[2][1].setText("O");
}
if(n1==7)
{
arr[0][2]=5;
jb[0][2].setText("O");
}
if(n1==8)
{
arr[1][2]=5;
jb[1][2].setText("O");
}
if(n1==9)
{
arr[2][2]=5;
jb[2][2].setText("O");
}
}
else
{
int cou=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{

if(arr[i][j]==2)
{
if(cou<1)
{
arr[i][j]=5;
jb[i][j].setText("O");
cou++;
}

}
}
//new win(~D~,"Drawn");
}
}
}
turn++;
}





int posswin(char c)
{


if(c==~X~)
{
if(arr[0][0]*arr[1][1]*arr[2][2]==18)
{

if(arr[0][0]==2)
{
System.out.println(1);
return 1;
}
else
{
if(arr[1][1]==2)
{
System.out.println(5);

return 5;
}

else
{
System.out.println(9);

return 9;
}
}
}

else
{

if(arr[2][0]*arr[1][1]*arr[0][2]==18)
{

if(arr[2][0]==2)
{
System.out.println(3);

return 3;
}
else
{
if(arr[1][1]==2)
{
System.out.println(5);

return 5;
}
else
{
System.out.println(7);

return 7;
}
}
}
else
{
for(int i=0;i<3;i++)
{
if(arr[i][0]*arr[i][1]*arr[i][2]==18)
{
for(int j=0;j<3;j++)
{
if(arr[i][j]==2)
{
if(i==0)
{
if(j==0)
{
System.out.println(1);

return 1;
}
if(j==1)
{
System.out.println(4);

return 4;
}
if(j==2)
{
System.out.println(7);

return 7;
}

}
if(i==1)
{
if(j==0)
{
System.out.println(2);

return 2;
}
if(j==1)
{
System.out.println(5);

return 5;
}
if(j==2)
{
System.out.println(8);

return 8;
}

}
if(i==2)
{
if(j==0)
{
System.out.println(3);

return 3;
}
if(j==1)
{
System.out.println(6);

return 6;
}
if(j==2)
{
System.out.println(9);

return 9;
}

}
}
}
}
else
{
if(arr[0][i]*arr[1][i]*arr[2][i]==18)
{
for(int j=0;j<3;j++)
{
if(arr[j][i]==2)
{
if(i==0)
{
if(j==0)
{
System.out.println(1);

return 1;
}
if(j==1)
{
System.out.println(2);

return 2;
}
if(j==2)
{
System.out.println(3);

return 3;
}
}
if(i==1)
{
if(j==0)
{
System.out.println(4);

return 4;
}
if(j==1)
{
System.out.println(5);

return 5;
}
if(j==2)
{
System.out.println(6);

return 6;
}
} if(i==2)
if(i==2)
{
System.out.println("i==2");
if(j==0)
{
System.out.println(7);

return 7;
}
if(j==1)
{
System.out.println(8);

return 8;
}
if(j==2)
{
System.out.println("j==2");
System.out.println(9);

return 9;
}
}
}
}
}
/*else
{
System.out.println("1st"+0);

return 0;
}*/
}
}
}
System.out.println("2nd"+0);

return 0;
}
}
else
{
if(c==~O~)
{
if(arr[0][0]*arr[1][1]*arr[2][2]==50)
{
if(arr[0][0]==2)
{
System.out.println(1);

return 1;
}
else
{
if(arr[1][1]==2)
{
System.out.println(5);

return 5;
}
else
{
System.out.println(9);

return 9;
}
}
}
else
{
if(arr[2][0]*arr[1][1]*arr[0][2]==50)
{
if(arr[2][0]==2)
{
System.out.println(3);

return 3;
}
else
{
if(arr[1][1]==2)
{
System.out.println(5);

return 5;
}
else
{
System.out.println(7);

return 7;
}
}
}
else
{
for(int i=0;i<3;i++)
{
System.out.println("inside for");

if(arr[i][0]*arr[i][1]*arr[i][2]==50)
{
System.out.println("right");

for(int j=0;j<3;j++)
{
if(arr[i][j]==2)
{
System.out.println("akhane");

if(i==0)
{
if(j==0)
{
System.out.println(1);

return 1;
}
if(j==1)
{
System.out.println(4);

return 4;
}
if(j==2)
{
System.out.println(7);

return 7;
}

}
if(i==1)
{
System.out.println("i=1");

if(j==0)
{
System.out.println(2);

return 2;
}
if(j==1)
{
System.out.println(5);

return 5;
}
if(j==2)
{
System.out.println(8);

return 8;
}
}
if(i==2)
{
if(j==0)
{
System.out.println(3);

return 3;
}
if(j==1)
{
System.out.println(6);

return 6;
}
if(j==2)
{
System.out.println(9);

return 9;
}
}
}
}
}
else
{
if(arr[0][i]*arr[1][i]*arr[2][i]==50)
{
for(int j=0;j<3;j++)
{
if(arr[j][i]==2)
{
if(i==0)
{
if(j==0)
{
System.out.println(1);

return 1;
}
if(j==1)
{
System.out.println(2);

return 2;
}
if(j==2)
{
System.out.println(3);

return 3;
}
}
if(i==1)
{
if(j==0)
{
System.out.println(4);

return 4;
}
if(j==1)
{
System.out.println(5);

return 5;
}
if(j==2)
{
System.out.println(6);

return 6;
}
} if(i==2)
if(i==2)
{
if(j==0)
{
System.out.println(7);

return 7;
}
if(j==1)
{
System.out.println(8);

return 8;
}
if(j==2)
{
System.out.println(9);

return 9;
}
}
}
}
}

}
}
System.out.println("4yh"+0);

return 0;
}
}
}
else
{
System.out.println("5th"+0);

return 0;
}

}

}



int make2()
{

if(arr[1][1]==2)
{
return 5;
}
else
{
if(arr[1][0]==2)
{
return 2;
}
else
{
if(arr[0][1]==2)
{
return 4;
}
else
{
if(arr[2][1]==2)
{
return 6;
}
else
{
if(arr[1][2]==2)
{
return 8;
}
else
{
return 0;
}
}
}
}
}
}
}




class win extends JFrame implements ActionListener
{
String s="Match Drawn";
JMenuBar jmb;
JMenu jm1,jm3;
JMenuItem jmi1,jmi2,jmi4;
JLabel jl;

win(char c,String Pname)
{
//System.out.println(Pname);
if(c==~C~)
{
s="~"+Pname+"~"+" "+"Better Luck Next Time";

}
if(c==~P~)
{
s="~"+Pname+"~"+" "+"Have Won The Game";
}
if(c==~D~)
{
s="Match Drawn";
}

this.setTitle("TicTacToe");
jmb=new JMenuBar();

jm1=new JMenu("File");
jmi1=new JMenuItem("New");
jmi2=new JMenuItem("Exit");

jm1.add(jmi1);
jm1.addSeparator();
jm1.add(jmi2);

jmi1.addActionListener(this);
jmi2.addActionListener(this);


jm3=new JMenu("Player");
jmi4=new JMenuItem("Choose Player");

jm3.add(jmi4);

jmi4.addActionListener(this);

jmb.add(jm1);
jmb.add(jm3);

setJMenuBar(jmb);

jl=new JLabel(s);
jl.setBounds(200,230,20,200);
this.add(jl);

this.setSize(400,300);
this.setLocation(120,90);
this.setResizable(false);
this.setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}




public void actionPerformed(ActionEvent e)
{

JMenuItem jmi=(JMenuItem)e.getSource();

if(jmi==jmi1)
{
UserInterface uf=new UserInterface();
uf.setSize(400,300);
uf.setLocation(120,90);
uf.setResizable(false);
uf.setVisible(true);
}

if(jmi==jmi2)
{
System.exit(0);
}


if(jmi==jmi4)
{
boolean flag=true;
String Pname=JOptionPane.showInputDialog("Enter Your Name..... ");
String Po=JOptionPane.showInputDialog("If u want to play as Leading player type ~1~ else type ~2~");
Pname=Pname.trim();
int p=Integer.parseInt(Po.trim());

this.setVisible(false);
Board b=new Board(Pname,p);
b.setSize(400,300);
b.setLocation(120,90);
b.setResizable(false);
b.setLayout(null);
b.setVisible(true);
}

}
}


class Final extends JFrame implements ActionListener
{
JButton jb[][]=new JButton[3][3];
Final(Board b)
{
this.setTitle("TicTacToe");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(b.arr[i][j]==3)
this.jb[i][j]=new JButton("X");
if(b.arr[i][j]==5)
this.jb[i][j]=new JButton("O");
}

for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
this.jb[i][j].setBounds(0+i*130,0+j*80,130,80);
this.add(jb[i][j]);
this.jb[i][j].addActionListener(this);
}

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

}

public void actionPerformed(ActionEvent e)
{

JComponent jc=(JComponent)e.getSource();
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(jc==jb[i][j])
{
this.setVisible(false);
}
}
}
Continue Reading | comments
 
Copyright © 2011. B.Sc B.Tech MCA Ploytechnic Mini,Main Projects | Free Main Projcets Download | MCA |B.tech . All Rights Reserved
Company Info | Contact Us | Privacy policy | Term of use | Widget | Advertise with Us | Site map
Template Modify by Creating Website. Inpire by Darkmatter Rockettheme Proudly powered by Blogger