Thursday, May 14, 2009

What Is Inheritance?


A class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs.

For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and tandems. This relationship is shown in the following figure.

What Is a Message?


Software objects interact and communicate with each other using messages. This may be termed as argument or a parameter

A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior. Your bicycle hanging from a hook in the garage is just a bunch of titanium alloy and rubber; by itself, the bicycle is incapable of any activity. The bicycle is useful only when another object (you) interacts with it (pedal).

Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B

Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters.

The next figure shows the three components that comprise a message:
The object to which the message is addressed (YourBicycle)
The name of the method to perform (changeGears)
Any parameters needed by the method (lowerGear)

What Is an Object?


An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life.

They all have state and behavior. For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).

Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object.

Definition: An object is a software bundle of variables and related methods.

In addition to its variables, an object, say a bicycle would also have methods to brake, change the pedal cadence, and change gears. (The bike would not have a method for changing the speed of the bicycle, as the bike's speed is just a side effect of what gear it's in, how fast the rider is pedaling, whether the brakes are on, and how steep the hill is.) These methods are formally known as instance methods because they inspect or change the state of a particular bicycle instance.

The object diagrams show that the object's variables make up the center, or nucleus, of the object. Methods surround and hide the object's nucleus from other objects in the program. Packaging an object's variables within the protective custody of its methods is called encapsulation This conceptual picture of an object-a nucleus of variables packaged within a protective membrane of methods-is an ideal representation of an object and is the ideal that designers of object-oriented systems strive for. However, it's not the whole story. Often, for practical reasons, an object may wish to expose some of its variables or hide some of its methods.
• Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work.
• Information hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it. You don't need to understand the gear mechanism on your bike to use it.

Java Basics

History
James Gosling was not satisfied with C++. There were several insufficiencies which hindered his plans. So, he created his own. Initially called Oak by James Gosling for the Green Project. However, since that name was already taken, it was later named Java.

Language Features
Platform Independent – can run on any environment
Garbage Collection – objects are automatically destroyed from memory
Object Oriented
Multithreaded – can perform several tasks at the same time
Dynamically Linked - classes are loaded as needed

OOP Concepts
If you've never used an object-oriented language before, you need to understand the underlying concepts before you begin writing code. You need to understand what an object is, what a class is, how objects and classes are related, and how objects communicate by using messages. The first few sections of this trail describe the concepts behind object-oriented programming. The last section shows how these concepts translate into code.

Tuesday, May 1, 2007

WinDerivedClassCatTest

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

public class WinDerivedClassCatTest extends JFrame{

//ds
int row = 10, col = 10;
String output = "";

public static void main(String[] args){
WinDerivedClassCatTest cattest = new WinDerivedClassCatTest();
cattest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cattest.setBounds(150,150,400,300);
cattest.setVisible(true);
}

public WinDerivedClassCatTest(){
super("Inheritance Demo For Cats");

Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
pane.setBackground(new Color(250,100,50));

//add text area
JTextArea textarea = new JTextArea(row,col);
//pane.add(textarea);

DerivedClass aCat = new DerivedClass("Toger","Tiger");
Cat bCat = new Cat("Meeeiaow");

//output here

output += aCat+"\n";
output += bCat+"\n";

//display here
textarea.setText(output);
pane.add(textarea,BorderLayout.NORTH);
}
}

Cat

public class Cat extends SuperClass{

//name and breed
private String name;
private String breed;

public Cat(String animalName){
super("Cat");
name = animalName;
breed = "Unknown";
}

//animal constructor
public Cat(String animalName,String animalBreed){
super("Cat");
name = animalName;
breed = animalBreed;
}

//convert to String
public String toString(){
return super.toString() + "\n" + name + "is a" + breed + "type of cat.\n";
}
}

DerivedClass

public class DerivedClass extends SuperClass{
//name and breed
private String name;
private String breed;

public DerivedClass(String animalName){
super("Dog");
name = animalName;
breed = "Unknown";
}

//animal constructor
public DerivedClass(String animalName,String animalBreed){
super("Dog");
name = animalName;
breed = animalBreed;
}

//convert to string
public String toString(){
return super.toString() +"\n"+name+"is a"+breed+"type of dog.\n";
}
}

SuperClass

public class SuperClass{
//animal type
private String type;

public SuperClass(String animalType){
type = new String( animalType );
}

//conversion to string
public String toString(){
return "This is a type of" + type + ".";
}
}

SysFontInfo

import java.awt.*;
import java.awt.GraphicsEnvironment;
import java.awt.Dimension;
import javax.swing.*;
import java.io.*;
//import j2packs.BottomPanel;
//import j2packs.TopPanel;

public class SysFontInfo extends JFrame {

//cdm
String output ="", topTitle ="";
int count, txtrow, txtcol;

public static void main(String[] args){
SysFontInfo fontsavailable = new SysFontInfo();
fontsavailable.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
fontsavailable.setSize(400,300);
fontsavailable.setVisible(true);
}

public SysFontInfo(){

super("Fonts on this PlatForm");
displayFonts();
}

protected void displayFonts(){

Container pane = getContentPane();
pane.setBackground(Color.blue);
pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

JTextArea outputArea = new JTextArea(txtrow,txtcol);

Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension winSize = toolkit.getScreenSize();

output += "This computer has the following specs:\n";
output += "Screen resolution: " + toolkit.getScreenResolution();
output += "dots per inch.\n";
output += "Screen size: " + winSize.width + " x ";
output += winSize.height + "pixels\n";

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();

output += "Font available on this platform:\n";
for(count = 0;count < fontnames.length;count++){
output += "" + (count+1) + "" + fontnames[count] + "\n";
}

//display
outputArea.setText(output);
outputArea.setFont(new Font("Tahoma",Font.PLAIN,14));
outputArea.setEditable(false);
pane.add(outputArea);

JScrollPane scrollpane = new JScrollPane(outputArea);
pane.add(scrollpane);

//add top and bottom panel
//topTitle = "SYSTEM INFORMATION";
// pane.add(new TopPanel(topTitle), BorderLayout.NORTH);
// pane.add(new BottomPanel(), BorderLayout.SOUTH);
}
}

Monday, April 16, 2007

Prime Factors

import javax.swing.*;

public class Prime_Factors{
public static void main(String[] args){
Prime_Factors factors=new Prime_Factors();
}
public Prime_Factors(){
String output="",input;
int num,count,h=0,get[]=new int[100],a=0;

input= JOptionPane.showInputDialog("Enter a number:");

num=Integer.parseInt(input);
do{
for(int x=2;x<=num;x++)
{
count=0;
for(int z=1;z<=num;z++)
{

if (x%z==0)
{
count=count+1;
}
}
if (count==2)
{
get[h]=x;
h++;
}
}
if(num%get[a]==0)
{
output+=get[a]+" ";
num=num/get[a];
}
if(num%get[a]!=0 && num!=0)
a++;
{
if(num%get[a]==0)
{
output+=get[a]+" ";
num=num/get[a];
}
}

}while(num!=1);

JOptionPane.showMessageDialog(null,output,"Prime Numbers",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

Pascal Triangle

import javax.swing.*;

public class Pascal{
public static void main(String[] args){
Pascal pas=new Pascal();
}
public Pascal(){
String output="",input;
int num,a,b;

input=JOptionPane.showInputDialog("Enter a number:");
num=Integer.parseInt(input);

for (int x=1;x<=num;x++)
{
for (int z=num;z>=x;z--)
{
output+=" ";
}
output+="1"+" ";
b=1;a=0;
for(int y=x;y>1;y--)
{
b=(y*b)/(a+1);
output+=b+" ";
a++;
}
output+="1";
output+="\n";
}




JOptionPane.showMessageDialog(null,output,"PASCAL TRIANGLE",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

FlowLayout

import javax.swing.*;
import java.awt.*;
public class FlowLayoutTest extends JFrame{
public static void main(String[] args){
FlowLayoutTest flowlayout = new FlowLayoutTest();
flowlayout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
flowlayout.setSize(400,300);
flowlayout.setVisible(true);
}
public FlowLayoutTest(){
super("FlowLayout Manager");
Container pane = getContentPane();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.add(new JLabel("This is a flowlayout test"));
JButton button = new JButton("FlowLayout");
button.setBorder(BorderFactory.createRaisedBevelBorder());
pane.add(button);
pane.add(new JTextField(30));
pane.add(new JTextArea("This is the textarea of this FlowLayout", 5,10));
pane.add(new JLabel("This is the label created by flowlayout"));
pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}

FIBONACCI

import javax.swing.*;

public class Fib{
public static void main(String[] args){
Fib fb=new Fib();
}
public Fib(){
String output="",input;
int num,a,b,sum=0;

input= JOptionPane.showInputDialog("Enter a number:");

num=Integer.parseInt(input);


a=0;
b=1;
for(int x=1;x<=num;x++)
{
sum=a+b;
a=b;
b=sum;
output+=sum+" ";
output+="\n";
}
JOptionPane.showMessageDialog(null,output,"Jo!!,THIS IS A FIBONACCI...BABY",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

BookSale

import java.text.*;
import javax.swing.text.MaskFormatter;
import java.text.Format.*;
import java.text.ParseException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.*;
import java.util.*;
import java.util.Calendar;
import java.text.DateFormatSymbols;
import java.sql.*;



//CLASS OF frame 2 FOR STUDENT FILE

class BookSale extends JFrame{
//ds
String output="";
private Container pane = getContentPane();
private JTable table;
private Connection con;
int row=300,col=3;
private JLabel pic2, label, label1, label2, label3, label4,label5,label6,label7,label8,label9;
private JTextField field1, field2, field3, field4, field5, field6, field7,field8;
//JComboBox combo1, combo2, combo3;
//private String gender[] = {"Male","Female"};
//private String semester[] = {"First", "Second", "Summer"};
//private String status[] = {"New", "Old/Active", "Returnee", "Transferee"};


public BookSale()
{
setTitle("BOOK SALES FORM");

JTextArea textarea;

pane.setBackground(Color.black);
pane.setLayout(null);
Font font = new Font("Teletype",Font.PLAIN,18);


JLabel label = new JLabel("COR JESU COLLEGE\n Digos City",JLabel.CENTER);
label.setFont(font);
label.setBounds(50,10,400,40);
label.setForeground(Color.pink);
label.setBackground(Color.yellow);
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label,BorderLayout.CENTER);


//for pictures or logo
Icon logo = new ImageIcon("logo3.gif");
pic2 = new JLabel(logo);
pic2.setBounds(50,0,60,60);
pane.add(pic2);

//SET DATE HERE
textarea = new JTextArea();
GregorianCalendar today = new GregorianCalendar();

String[]weekdays = new DateFormatSymbols().getWeekdays();
String[]months = new DateFormatSymbols().getMonths();

output+=""+weekdays[today.get(today.DAY_OF_WEEK)];
output+=", "+(today.get(today.DATE))+" ";
output+=months[today.get(today.MONTH)]+"";
output+=today.get(today.YEAR)+"\n";

//LABELS HERE
label = new JLabel("B O O K S A L E F O R M");
label.setBounds(100,60,350,50);
label.setFont(new Font("Broadway BT",Font.BOLD,18));
label.setForeground(Color.yellow);
label.setBackground(Color.blue);
pane.add(label);


label1 = new JLabel("Date:");
label1.setBounds(280,120,200,20);
label1.setFont(new Font("Tahoma",Font.PLAIN,14));
label1.setForeground(Color.white);
pane.add(label1);


textarea.setFont(new Font("Tahoma",Font.PLAIN,14));
textarea.setEditable(false);
textarea.setText(output);
textarea.setBounds(320,120,180,20);
textarea.setForeground(Color.pink);
textarea.setBackground(Color.black);
pane.add(textarea);


label3 = new JLabel("Name:");
label3.setBounds(10,120,250,20);
label3.setFont(new Font("Tahoma",Font.PLAIN,14));
label3.setForeground(Color.white);
pane.add(label3);
field3 = new JTextField();
field3.setBounds(50,120,200,20);
field3.setText("");
field3.setFont(new Font("Tahoma",Font.PLAIN,16));
field3.setForeground(Color.blue);
pane.add(field3);
//pane.add(table);



//FOR TABLE
//JTable inventTable = new JTable(row,col);
// inventTable.setGridColor(Color.gray);

//JScrollPane inventScroll = new JScrollPane(inventTable);
//inventScroll.setBounds(20,150,450,100);
//pane.add(inventScroll);


label4 = new JLabel("TOTAL P:");
label4.setBounds(300,270,150,20);
label4.setFont(new Font("Tahoma",Font.PLAIN,14));
label4.setForeground(Color.white);
pane.add(label4);
field4 = new JTextField();
field4.setBounds(360,270,120,20);
field4.setText("");
field4.setFont(new Font("Tahoma",Font.PLAIN,16));
field4.setForeground(Color.blue);
pane.add(field4);


label5 = new JLabel("Receive Payment By:");
label5.setBounds(150,310,150,20);
label5.setFont(new Font("Tahoma",Font.PLAIN,14));
label5.setForeground(Color.white);
pane.add(label5);
field5 = new JTextField();
field5.setBounds(290,310,190,20);
field5.setText("");
field5.setFont(new Font("Tahoma",Font.PLAIN,16));
field5.setForeground(Color.blue);
pane.add(field5);


label6 = new JLabel("Cashier");
label6.setBounds(360,330,250,20);
label6.setFont(new Font("Tahoma",Font.PLAIN,14));
label6.setForeground(Color.white);
pane.add(label6);

label7 = new JLabel("O.R. Number:");
label7.setBounds(290,360,150,20);
label7.setFont(new Font("Tahoma",Font.PLAIN,14));
label7.setForeground(Color.white);
pane.add(label7);
field7 = new JTextField();
field7.setBounds(375,360,105,20);
field7.setText("");
field7.setFont(new Font("Tahoma",Font.PLAIN,16));
field7.setForeground(Color.blue);
pane.add(field7);

label8 = new JLabel("Recieved in Good Condition By:");
label8.setBounds(120,390,250,20);
label8.setFont(new Font("Tahoma",Font.PLAIN,14));
label8.setForeground(Color.white);
pane.add(label8);
field8 = new JTextField();
field8.setBounds(290,390,190,20);
field8.setText("");
field8.setFont(new Font("Tahoma",Font.PLAIN,16));
field8.setForeground(Color.blue);
pane.add(field8);

label9 = new JLabel("Parent/Guardian/Student");
label9.setBounds(300,410,250,20);
label9.setFont(new Font("Tahoma",Font.PLAIN,14));
label9.setForeground(Color.white);
pane.add(label9);

JPanel bottompanel=new JPanel();
bottompanel.setBackground(Color.white);

JButton buttonnew;
JButton buttonsave;
JButton buttonsearch;
JButton buttonprint;
JButton buttonclose;
JButton buttondelete;


//dimension size of button
Dimension size=new Dimension(50,30);
//bevel JLabel label1 = newbutton
Border edge=BorderFactory.createRaisedBevelBorder();

//declare bottons



buttonnew = new JButton("NEW");
buttonnew.setBounds(10,460,60,30);
buttonnew.setPreferredSize(size);
buttonnew.setBorder(edge);
buttonnew.setToolTipText("click this button to add file.");
buttonnew.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonnew.setFont(new Font("Arial",Font.BOLD,14));
buttonnew.setBackground(new Color(10,250,210));
buttonnew.setForeground(new Color(0,5,255));
buttonnew.setMnemonic('N');
bottompanel.add(buttonnew);

buttonsave = new JButton("SAVE");
buttonsave.setPreferredSize(size);
buttonsave.setBorder(edge);
buttonsave.setToolTipText("it saves the files");
buttonsave.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonsave.setFont(new Font("Arial",Font.BOLD,14));
buttonsave.setForeground(new Color(0,5,255));
buttonsave.setBackground(new Color(10,250,210));
buttonsave.setBounds(100,460,60,30);
buttonsave.setMnemonic('S');
bottompanel.add(buttonsave);

buttonprint = new JButton("PRINT");
buttonprint.setBounds(190,460,60,30);
buttonprint.setPreferredSize(size);
buttonprint.setBorder(edge);
buttonprint.setToolTipText("it gives you a hard copy");
buttonprint.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonprint.setFont(new Font("Arial",Font.BOLD,14));
buttonprint.setForeground(new Color(0,5,255));
buttonprint.setBackground(new Color(10,250,210));
buttonprint.setMnemonic('P');
bottompanel.add(buttonprint);

buttonsearch = new JButton("SEARCH");
buttonsearch.setBounds(280,460,60,30);
buttonsearch.setPreferredSize(size);
buttonsearch.setBorder(edge);
buttonsearch.setToolTipText("click this button to find");
buttonsearch.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonsearch.setFont(new Font("Arial",Font.BOLD,14));
buttonsearch.setForeground(new Color(0,5,255));
buttonsearch.setBackground(new Color(10,250,210));
buttonsearch.setMnemonic('R');
bottompanel.add(buttonsearch);

buttondelete = new JButton("DELETE");
buttondelete.setBounds(370,460,60,30);
buttondelete.setPreferredSize(size);
buttondelete.setBorder(edge);
buttondelete.setToolTipText("Click this button to erase the file"); buttondelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttondelete.setFont(new Font("Arial",Font.BOLD,14));
buttondelete.setForeground(new Color(0,5,255));
buttondelete.setBackground(new Color(10,250,210));
buttondelete.setMnemonic('D');
bottompanel.add(buttondelete);


buttonclose = new JButton("CLOSE");
buttonclose.setBounds(460,460,60,30);
buttonclose.setPreferredSize(size);
buttonclose.setBorder(edge);
buttonclose.setToolTipText("Click this button to terminate the frame"); buttonclose.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonclose.setFont(new Font("Arial",Font.BOLD,14));
buttonclose.setForeground(new Color(0,5,255));
buttonclose.setBackground(new Color(10,250,210));
buttonclose.setMnemonic('C');
bottompanel.add(buttonclose);

//pane.add(bottompanel);
pane.add(buttonsearch);
pane.add(buttonnew);
pane.add(buttonprint);
pane.add(buttonsave);
pane.add(buttonclose);
pane.add(buttondelete);


buttonclose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
}
}
);






//display table



String url = "jdbc:odbc:cim";
// pane.setLayout(null);

// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );

con = DriverManager.getConnection(
url );
}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}

getTable();

setSize( 450, 150 );
show();
}

private void getTable()
{
Statement statement;
ResultSet resultSet;

try {
String query = "SELECT * FROM Table1";

statement = con.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}

private void displayResultSet( ResultSet rs )
throws SQLException
{
// position to first record
boolean moreRecords = rs.next();

// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}

setTitle( "Authors table from Books" );

Vector columnHeads = new Vector();
Vector rows = new Vector();

try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );

// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );

// display table with ResultSet contents
table = new JTable(rows, columnHeads);
JScrollPane scroller = new JScrollPane( table );
scroller.setBounds(50,150,430,100);
pane.add(scroller);
//getContentPane().add(scroller, BorderLayout.CENTER );
validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}

private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
{
Vector currentRow = new Vector();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}

return currentRow;
}
}

BirthDay

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*;
import java.text.DateFormatSymbols;
import java.util.Calendar;

public class BDay extends JFrame{
int row,col;
Container pane;
JTextArea textArea;
String output=" ",inputbd,Name;
String fdt="MM/dd/yyyy";
public static void main(String[] args){
BDay brtdy=new BDay();
brtdy.setBounds(100,100,350,250);
brtdy.setVisible(true);
}

public BDay(){
super("HAPPY BIRTHDAY");
pane=getContentPane();
pane.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));

textArea=new JTextArea(row,col);
addWindowListener(new WindowHandler());
input();
textArea.setText(output);
pane.add(textArea);
pane.add(new TopPanel(),BorderLayout.NORTH);
pane.add(new BottomPanel(),BorderLayout.SOUTH);
}
void input(){
String dformat,dform;
int age;
Name=JOptionPane.showInputDialog("Enter Name:");
inputbd = JOptionPane.showInputDialog("Enter Date Of Birth in this form "+"\n"+"Example:\n 01/25/1940");
try{
SimpleDateFormat df= new SimpleDateFormat(fdt);
df.setLenient(false);
java.util.Date d = df.parse(inputbd);
Calendar dateofbirth = Calendar.getInstance();
dateofbirth.setTime(d);
Calendar today = Calendar.getInstance();
age = today.get(Calendar.YEAR) - dateofbirth.get(Calendar.YEAR);
dformat = " MMMM, dd,EEEE--yyyy";
dform="MM,dd,yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dformat);
SimpleDateFormat sdf2 = new SimpleDateFormat(dform);
output +="Name:"+ Name + "\n\n";
output +="Date of Birth:"+sdf2.format(dateofbirth.getTime())+"\n";
output+="You were born:" + " " + sdf.format(dateofbirth.getTime())+ "\n\n";
dateofbirth.set(Calendar.YEAR,2002);
output +="You are"+" "+age+" "+"years old this year:"+" "+sdf.format(dateofbirth.getTime());
}
catch(ParseException e){

JOptionPane.showMessageDialog(null,"Date is invalid ","Try another",JOptionPane.ERROR_MESSAGE);

}
}

class WindowHandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
}

BankServer

import java.sql.*;
import java.sql.Date.*;
import javax.swing.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.event.*;
import java.io.*;
import java.util.Calendar.*;
import java.util.Date.*;
import java.text.*;
import java.net.*;

class BankServer extends JFrame {
private JTabbedPane tabbedPane;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JButton addbutton;
private JTextField field,field2,fie1,fie2,fie3,fiee1,fiee2,fiee3;
private String amm="";
ObjectOutputStream output;
ObjectInputStream input;
private JTextArea display;
private int amountt;

public BankServer()
{
setTitle( "Banking Program" );
setSize( 400, 300 );
setBackground( Color.gray );

JPanel topPanel = new JPanel();
display = new JTextArea();
field = new JTextField();
field2 = new JTextField();
fie1 = new JTextField();
fie2 = new JTextField();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createPage1();
createPage2();
createPage3();

// Create a tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Add Client", panel1 );
tabbedPane.addTab( "With Draw", panel2 );
tabbedPane.addTab( "Deposit", panel3 );
topPanel.add( tabbedPane, BorderLayout.CENTER );

}

public void runServer(){
ServerSocket server;
Socket connection;
int counter = 1;
try{ server = new ServerSocket(5000,100);
while(true){
display.setText("Waiting for connection\n");
connection = server.accept();
display.append("Connection"+ counter + " recieved from: " + connection.getInetAddress().getHostName());
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
display.append("\n Got I/O stream\n");
String message ="";// "SERVER>> Connection Succesfull";
do{
try {

String getrequest=(String) input.readObject();
if(getrequest.equals("add")){
String oktoadd= "oktoadd";
output.writeObject(oktoadd);
//field.setText((String) input.readObject());
//field2.setText((String)input.readObject());

field.setText((String) input.readObject());
field2.setText((String)input.readObject());
String okk=(String)input.readObject();
if(okk.equals("ok")){
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();

st.executeUpdate("INSERT INTO ClientTable( Client_ID , Name) "+
" VALUES ( '" + field.getText()+"','" + field2.getText() + "') ");
con.close();
JOptionPane.showMessageDialog(null,"Enroll is Succesfull");
field.setText("");
field2.setText("");
} catch (java.lang.Exception ex){
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Add is not Succesfull");
field.setText("");
field2.setText("");
String eror="error";
//output.writeObject(eror);
senderror(eror);
}
}//end if
} //end if

if(getrequest.equals("withdraw")){
String oktowithdraw= "oktowithdraw";
output.writeObject(oktowithdraw);
fie1.setText((String) input.readObject());
String mewith = fie1.getText(),oo="ok";
if(oo.equals("ok")){
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();
String query1= "SELECT * FROM ClientTable WHERE Client_ID='"+fie1.getText()+"' ";
ResultSet rs1 = st.executeQuery(query1);
rs1.next();

fie2.setText(rs1.getString(2));
String name = fie2.getText();
//output.writeObject(name);
sendData(name);
} catch (java.lang.Exception ex)
{
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"invalid Client ID or None in database");
}
}//end if sa withdraw....

//fie2.setText(
//String okk=(String)input.readObject();


}
}
catch(ClassNotFoundException cnfex){
display.append("\nUnknown object type received");
}
}while(!message.equals("CLIENT>>> TERMINATE"));
display.append("\n User terminated connection");
//enter.setEnabled(false);
output.close();
input.close();
connection.close();
++counter;
}
}
catch(IOException io){
io.printStackTrace();
}
}

public void createPage1() {
panel1 = new JPanel();
panel1.setLayout( null );

JLabel label1 = new JLabel( "Client ID:" );
label1.setBounds( 10, 15, 150, 20 );
panel1.add( label1 );

//field = new JTextField();
field.setBounds( 60, 15, 80, 20 );
panel1.add( field );

JLabel label2 = new JLabel( "Name:" );
label2.setBounds( 10, 45, 150, 20 );
panel1.add( label2 );

//field2 = new JTextField();
field2.setBounds( 60, 45, 150, 20 );
panel1.add( field2 );
addbutton = new JButton("Add");
display.setBounds(50, 150, 230, 75 );
display.setEditable(false);
panel1.add(display);
addbutton.setBounds(100, 100, 90, 20 );
addbutton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();

st.executeUpdate("INSERT INTO ClientTable( Client_ID , Name) "+
" VALUES ( '" + field.getText()+"','" + field2.getText() + "') ");
con.close();
//JOptionPane.showMessageDialog(null,"Enroll is Succesfull");
field.setText("");
field2.setText("");
} catch (java.lang.Exception ex){
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Add is not Succesfull");

field.setText("");
field2.setText("");
}
}
});
panel1.add( addbutton);
}

public void createPage2() {
panel2 = new JPanel();
panel2.setLayout( null);
panel2.setBackground( Color.blue );
JLabel lab1 = new JLabel( "Client ID:" );
lab1.setBounds( 10, 15, 150, 20 );
panel2.add( lab1 );

//fie1 = new JTextField();
fie1.setBounds( 60, 15, 80, 20 );
panel2.add( fie1 );

JLabel lab2 = new JLabel( "Name:" );
lab2.setBounds( 10, 45, 150, 20 );
panel2.add( lab2 );

//fie2 = new JTextField();
fie2.setBounds( 60, 45, 150, 20 );
fie2.setEditable(false);
panel2.add( fie2 );
JLabel amount = new JLabel("Amount:");
amount.setBounds( 10, 70, 150, 20 );
panel2.add(amount);
fie3 = new JTextField();
fie3.setBounds( 60, 70, 150, 20 );

panel2.add(fie3);
fie1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();
String query1= "SELECT * FROM ClientTable WHERE Client_ID='"+fie1.getText()+"' ";
ResultSet rs1 = st.executeQuery(query1);
rs1.next();

fie2.setText(rs1.getString(2));

} catch (java.lang.Exception ex)
{
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"invalid Client ID or None in database");
}
}
});
JButton okbutton = new JButton("with draw");
okbutton.setBounds(100, 100, 90, 20 );

okbutton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
amm = fie3.getText();
amountt = Integer.parseInt(amm);
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO ClientWithdraw( Client_ID , Amount) "+
" VALUES ( '" + fie1.getText()+"','" + amountt + "') ");
con.close();
JOptionPane.showMessageDialog(null,"WithDraw is Succesfull");

} catch (java.lang.Exception ex)
{
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Add is not Succesfull");
}
}
});
panel2.add( okbutton);
}

private void senderror( String s ) {
try {
//message = s;
output.writeObject ( s );
output.flush();
//display.append ( "\nCLIENT>>> " + s );
}
catch ( IOException cnfe ) {
display.append ( "\nError writing object" );
}
}
private void sendData( String s ) {
try {
//message = s;
output.writeObject ( s );
output.flush();
//display.append ( "\nCLIENT>>> " + s );
}
catch ( IOException cnfe ) {
display.append ( "\nError writing object" );
}
}

public void createPage3()
{
panel3 = new JPanel();
panel3.setLayout( null );
panel3.setBackground( Color.orange );

JLabel labb1 = new JLabel( "Client ID:" );
labb1.setBounds( 10, 15, 150, 20 );
panel3.add( labb1 );

JTextField fiee1 = new JTextField();
fiee1.setBounds( 60, 15, 80, 20 );
panel3.add( fiee1 );

JLabel labb2 = new JLabel( "Name:" );
labb2.setBounds( 10, 45, 150, 20 );
panel3.add( labb2 );

JTextField fiee2 = new JTextField();
fiee2.setBounds( 60, 45, 150, 20 );
fiee2.setEditable(false);
panel3.add( fiee2 );
JLabel amoun = new JLabel("Amount:");
amoun.setBounds( 10, 70, 150, 20 );
panel3.add(amoun);
fiee3 = new JTextField();
fiee3.setBounds( 60, 70, 150, 20 );
panel3.add(fiee3);
JButton okkbutton = new JButton("deposit");
okkbutton.setBounds(100, 100, 90, 20 );

panel3.add( okkbutton);
}

public static void main( String args[] )
{
// Create an instance of the test application
BankServer mainFrame = new BankServer();
mainFrame.setVisible( true );
mainFrame.runServer();
}
}

Bank

import java.sql.Date.*;
import javax.swing.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.event.*;
import java.io.*;
import java.util.Calendar.*;
import java.util.Date.*;
import java.text.*;
import java.net.*;

class Bank extends JFrame {
private JTabbedPane tabbedPane;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JButton addbutton;
private JTextField field,field2,fie1,fie2,fie3,fiee1,fiee2,fiee3;
private String amm="";
private int amountt;
JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;
Socket client;

public Bank()
{
setTitle( "Banking Program" );
setSize( 400, 300 );
setBackground( Color.gray );


JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createPage1();
createPage2();
createPage3();

// Create a tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Add Client", panel1 );
tabbedPane.addTab( "With Draw", panel2 );
tabbedPane.addTab( "Deposit", panel3 );
topPanel.add( tabbedPane, BorderLayout.CENTER );

}

public void createPage1() {
panel1 = new JPanel();
panel1.setLayout( null );

JLabel label1 = new JLabel( "Client ID:" );
label1.setBounds( 10, 15, 150, 20 );
panel1.add( label1 );

field = new JTextField();
field.setBounds( 60, 15, 80, 20 );
panel1.add( field );

JLabel label2 = new JLabel( "Name:" );
label2.setBounds( 10, 45, 150, 20 );
panel1.add( label2 );

field2 = new JTextField();
field2.setBounds( 60, 45, 150, 20 );
panel1.add( field2 );
addbutton = new JButton("Add");
addbutton.setBounds(100, 100, 90, 20 );
addbutton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {

try {
client = new Socket ( InetAddress.getByName ( "202.134.238.3" ), 10000 );
output = new ObjectOutputStream ( client.getOutputStream() );
output.flush();
String mess =field.getText();
String mess1 =field2.getText();//kini sad....
field.setCaretPosition ( field.getText().length() );
output.writeObject(mess);
output.writeObject(mess1);//kini
field2.setCaretPosition ( field2.getText().length() );
output.flush();
// field.getText()+"','" + field2.getText()

field.setText("");
field2.setText("");

} catch (java.lang.Exception ex){
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Add is not Succesfull");
field.setText("");
field2.setText("");
}
}
});
panel1.add( addbutton);
}

public void createPage2() {
panel2 = new JPanel();
panel2.setLayout( null);
panel2.setBackground( Color.blue );
JLabel lab1 = new JLabel( "Client ID:" );
lab1.setBounds( 10, 15, 150, 20 );
panel2.add( lab1 );

fie1 = new JTextField();
fie1.setBounds( 60, 15, 80, 20 );
panel2.add( fie1 );

JLabel lab2 = new JLabel( "Name:" );
lab2.setBounds( 10, 45, 150, 20 );
panel2.add( lab2 );

fie2 = new JTextField();
fie2.setBounds( 60, 45, 150, 20 );
fie2.setEditable(false);
panel2.add( fie2 );
JLabel amount = new JLabel("Amount:");
amount.setBounds( 10, 70, 150, 20 );
panel2.add(amount);
fie3 = new JTextField();
fie3.setBounds( 60, 70, 150, 20 );

panel2.add(fie3);
fie1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Bank";
Connection con = DriverManager.getConnection(url,"awing","awing");
Statement st = con.createStatement();
String query1= "SELECT * FROM ClientTable WHERE Client_ID='"+fie1.getText()+"' ";
ResultSet rs1 = st.executeQuery(query1);
rs1.next();

fie2.setText(rs1.getString(2));

} catch (java.lang.Exception ex)
{
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"invalid Client ID or None in database");
}
}
});
JButton okbutton = new JButton("with draw");
okbutton.setBounds(100, 100, 90, 20 );


okbutton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {

amm = fie3.getText();
amountt = Integer.parseInt(amm);
try {


} catch (java.lang.Exception ex)
{
//ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Add is not Succesfull");
}
}
});
panel2.add( okbutton);
}

public void createPage3()
{
panel3 = new JPanel();
panel3.setLayout( null );
panel3.setBackground( Color.orange );

JLabel labb1 = new JLabel( "Client ID:" );
labb1.setBounds( 10, 15, 150, 20 );
panel3.add( labb1 );

JTextField fiee1 = new JTextField();
fiee1.setBounds( 60, 15, 80, 20 );
panel3.add( fiee1 );

JLabel labb2 = new JLabel( "Name:" );
labb2.setBounds( 10, 45, 150, 20 );
panel3.add( labb2 );

JTextField fiee2 = new JTextField();
fiee2.setBounds( 60, 45, 150, 20 );
fiee2.setEditable(false);
panel3.add( fiee2 );
JLabel amoun = new JLabel("Amount:");
amoun.setBounds( 10, 70, 150, 20 );
panel3.add(amoun);
fiee3 = new JTextField();
fiee3.setBounds( 60, 70, 150, 20 );
panel3.add(fiee3);
JButton okkbutton = new JButton("deposit");
okkbutton.setBounds(100, 100, 90, 20 );

panel3.add( okkbutton);
}

// Main method to get things started
public static void main( String args[] )
{
// Create an instance of the test application
Bank mainFrame = new Bank();
mainFrame.setVisible( true );
}
}


Arc

/*
* @(#)Arcs.java 1.19 01/12/03
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java2d.demos.Arcs_Curves;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Arc2D;
import java.awt.geom.AffineTransform;
import java2d.AnimatingSurface;


/**
* Arc2D Open, Chord & Pie arcs; Animated Pie Arc.
*/
public class Arcs extends AnimatingSurface {

private static String types[] = {"Arc2D.OPEN","Arc2D.CHORD","Arc2D.PIE"};
private static final int CLOSE = 0;
private static final int OPEN = 1;
private static final int FORWARD = 0;
private static final int BACKWARD = 1;
private static final int DOWN = 2;
private static final int UP = 3;

private int aw, ah; // animated arc width & height
private int x, y;
private int angleStart = 45;
private int angleExtent = 270;
private int mouth = CLOSE;
private int direction = FORWARD;


public Arcs() {
setBackground(Color.white);
}


public void reset(int w, int h) {
x = 0; y = 0;
aw = w/12; ah = h/12;
}


public void step(int w, int h) {
// Compute direction
if (x+aw >= w-5 && direction == FORWARD)
direction = DOWN;
if (y+ah >= h-5 && direction == DOWN)
direction = BACKWARD;
if (x-aw <= 5 && direction == BACKWARD)
direction = UP;
if (y-ah <= 5 && direction == UP)
direction = FORWARD;

// compute angle start & extent
if (mouth == CLOSE) {
angleStart -= 5;
angleExtent += 10;
}
if (mouth == OPEN) {
angleStart += 5;
angleExtent -= 10;
}
if (direction == FORWARD) {
x += 5; y = 0;
}
if (direction == DOWN) {
x = w; y += 5;
}
if (direction == BACKWARD) {
x -= 5; y = h;
}
if (direction == UP) {
x = 0; y -= 5;
}
if (angleStart == 0)
mouth = OPEN;
if (angleStart > 45)
mouth = CLOSE;
}


public void render(int w, int h, Graphics2D g2) {

g2.setStroke(new BasicStroke(5.0f));
// Draw Arcs
for (int i = 0; i < types.length; i++) {
Arc2D arc = new Arc2D.Float(i);
arc.setFrame((i+1)*w*.2, (i+1)*h*.2, w*.17, h*.17);
arc.setAngleStart(45);
arc.setAngleExtent(270);
g2.setColor(Color.blue);
g2.draw(arc);
g2.setColor(Color.gray);
g2.fill(arc);
g2.setColor(Color.black);
g2.drawString(types[i], (int)((i+1)*w*.2), (int)((i+1)*h*.2-3));
}

// Draw Animated Pie Arc
Arc2D pieArc = new Arc2D.Float(Arc2D.PIE);
pieArc.setFrame(0, 0, aw, ah);
pieArc.setAngleStart(angleStart);
pieArc.setAngleExtent(angleExtent);
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
switch (direction) {
case DOWN : at.rotate(Math.toRadians(90)); break;
case BACKWARD : at.rotate(Math.toRadians(180)); break;
case UP : at.rotate(Math.toRadians(270));
}
g2.setColor(Color.blue);
g2.fill(at.createTransformedShape(pieArc));
}


public static void main(String argv[]) {
createDemoFrame(new Arcs());
}
}

Friday, April 13, 2007

AquaMetalTheme

/*
* @(#)AquaMetalTheme.java 1.6 01/12/03
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/


import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;

/**
* This class describes a theme using "blue-green" colors.
*
* @version 1.6 12/03/01
* @author Steve Wilson
*/
public class AquaMetalTheme extends DefaultMetalTheme {

public String getName() { return "Oxide"; }

private final ColorUIResource primary1 = new ColorUIResource(102, 153, 153);
private final ColorUIResource primary2 = new ColorUIResource(128, 192, 192);
private final ColorUIResource primary3 = new ColorUIResource(159, 235, 235);

protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }

}

AppletFrame

/*
* @(#)AppletFrame.java 1.10 01/12/03
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

import java.awt.Frame;
import java.awt.Event;
import java.awt.Dimension;
import java.applet.Applet;
import java.awt.AWTEvent;

// Applet to Application Frame window
class AppletFrame extends Frame
{

public static void startApplet(String className,
String title,
String args[])
{
// local variables
Applet a;
Dimension appletSize;

try
{
// create an instance of your applet class
a = (Applet) Class.forName(className).newInstance();
}
catch (ClassNotFoundException e) { return; }
catch (InstantiationException e) { return; }
catch (IllegalAccessException e) { return; }

// initialize the applet
a.init();
a.start();

// create new application frame window
AppletFrame f = new AppletFrame(title);

// add applet to frame window
f.add("Center", a);

// resize frame window to fit applet
// assumes that the applet sets its own size
// otherwise, you should set a specific size here.
appletSize = a.getSize();
f.pack();
f.setSize(appletSize);

// show the window
f.show();

} // end startApplet()


// constructor needed to pass window title to class Frame
public AppletFrame(String name)
{
// call java.awt.Frame(String) constructor
super(name);
}

// needed to allow window close
public void processEvent(AWTEvent e)
{
// Window Destroy event
if (e.getID() == Event.WINDOW_DESTROY)
{
// exit the program
System.exit(0);
}
} // end handleEvent()

} // end class AppletFrame