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

AddNumbers

import javax.swing.*;

public class Add2numbers{

public static void main(String[] args){
Add2numbers add=new Add2numbers();

}
public Add2numbers(){
String num1,num2,output="";
int no1,no2,sum=0;

num1=JOptionPane.showInputDialog(null,"Enter 1st to add","INPUT NO1",JOptionPane.QUESTION_MESSAGE);
num2=JOptionPane.showInputDialog(null,"Enter 2nd to add","INPUT NO2",JOptionPane.QUESTION_MESSAGE);

no1=Integer.parseInt(num1);
no2=Integer.parseInt(num2);

sum=no1+no2;

output+="first number entered is" + no1 +"\n";
output+="Second number entered is" + no2 +"\n";

JOptionPane.showMessageDialog(null,output+no1+"+"+no2+"="+sum,"sum",JOptionPane.INFORMATION_MESSAGE);

System.exit(0);
}
}

Action Button

public boolean action(Event evt, Object obj)
{
boolean retval = false; // assume not processed
if ("New".equals(obj))
{
if (validateFields())
{
try
{
CurrentOperator.insert(db);
readOperators();
}
catch(ComException e)
{
setStatus(e);
}
}
retval = true;
}
else if ("Update".equals(obj))
{
if (validateFields())
{
try
{
CurrentOperator.update(db);
readOperators();
}
catch(Exception e)
{
setStatus("DB Error: " + e.getMessage());
}
}
retval = true;
}
return retval;
}
If the New button is pressed, the fields are validated and

Accounts Entry

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 javax.swing.DefaultCellEditor;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.text.*;
import javax.swing.text.MaskFormatter;
import java.text.Format.*;
import javax.swing.table.AbstractTableModel;


//CLASS OF frame 2 FOR STUDENT FILE

class AccountsEntry extends JFrame{
//ds
String output="";
int row=200, col=5;
private JLabel pic2, label, label1, label2, label3, label4,label5,label6,label7;
private JTextField field1, field2, field3, field4, field5, field6, field7;
private JTable inventTable;
private JScrollPane inventScroll1;
JComboBox combo1, combo2, combo3;
private String gender[] = {"Male","Female"};
private String semester[] = {"First", "Second", "Summer"};
private String status[] = {"New", "Old/Active", "Returnee", "Transferee"};
private JRadioButton student,staff;
private ButtonGroup radioGroup;

JButton buttonadd;
JButton buttonsave;
JButton buttonsearch;
JButton buttonprint;
JButton buttonclose;
JButton buttondelete;
JRadioButton buttonstudent;
JRadioButton buttonstaff;
ButtonGroup radiogroup;


public AccountsEntry()
{
setTitle("ACCOUNTS FORM");
Container pane = getContentPane();
JTextArea textarea;

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


JLabel label = new JLabel("CJC Center for Instructional and Mimeographing Services"+"\n"+" INVENTORY SYSTEM",JLabel.CENTER);
label.setFont(font);
label.setBounds(0,0,790,60);
label.setForeground(Color.yellow);
label.setBackground(Color.blue);
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
pane.add(label,BorderLayout.CENTER);


//for pictures or logo
Icon logo = new ImageIcon("logo2.gif");
pic2 = new JLabel(logo);
pic2.setBounds(0,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";

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

JScrollPane inventScroll = new JScrollPane(inventTable);
inventScroll.setBounds(30,280,650,150);
pane.add(inventScroll);

****************/

//LABELS HERE
label = new JLabel("A C C O U N T S E N T R Y");
label.setBounds(250,80,450,50);
label.setFont(new Font("Broadway BT",Font.BOLD,20));
label.setForeground(Color.red);
label.setBackground(Color.blue);
pane.add(label);


label1 = new JLabel("Date:");
label1.setBounds(555,150,200,20);
label1.setFont(new Font("Tahoma",Font.PLAIN,14));
label1.setForeground(Color.white);
pane.add(label1);
field1 = new JTextField();
field1.setBounds(592,150,160,20);
field1.setText(output);
field1.setForeground(Color.blue);
pane.add(field1);

label2 = new JLabel("ID Number:");
label2.setBounds(10,150,100,20);
label2.setFont(new Font("Tahoma",Font.PLAIN,14));
label2.setForeground(Color.white);
pane.add(label2);

try{
MaskFormatter mf1 = new MaskFormatter("####-####-#");
JFormattedTextField field2 = new JFormattedTextField(mf1);
field2.setBounds(85,150,80,20);
//field2.setText("");
field2.setForeground(Color.blue);
pane.add(field2);
}
catch(ParseException pe){
}
label3 = new JLabel("Name:");
label3.setBounds(10,200,250,20);
label3.setFont(new Font("Tahoma",Font.PLAIN,14));
label3.setForeground(Color.white);
pane.add(label3);
field3 = new JTextField();
field3.setBounds(85,200,250,20);
field3.setText("");
field3.setFont(new Font("Tahoma",Font.BOLD,14));
field3.setForeground(Color.blue);
pane.add(field3);

label4 = new JLabel("Status:");
label4.setBounds(190,150,105,20);
label4.setFont(new Font("Tahoma",Font.PLAIN,14));
label4.setForeground(Color.white);
pane.add(label4);

combo3 = new JComboBox(status);
combo3.setBounds(235,150,100,20);
combo3.setForeground(Color.blue);
pane.add(combo3);

label5 = new JLabel("Course/Year:");
label5.setBounds(585,200,100,20);
label5.setFont(new Font("Tahoma",Font.PLAIN,14));
label5.setForeground(Color.white);
pane.add(label5);

try{
MaskFormatter mf2 = new MaskFormatter("****-#");
JFormattedTextField field5 = new JFormattedTextField(mf2);
field5.setBounds(670,200,80,20);
//field5.setText("");
field5.setForeground(Color.blue);
pane.add(field5);
}
catch(ParseException pe){
}

label6 = new JLabel("Semester:");
label6.setBounds(360,150,100,20);
label6.setFont(new Font("Tahoma",Font.PLAIN,14));
label6.setForeground(Color.white);
pane.add(label6);

combo1 = new JComboBox(semester);
combo1.setBounds(425,150,100,20);
combo1.setForeground(Color.blue);
pane.add(combo1);

label7 = new JLabel("Gender:");
label7.setBounds(375,200,100,20);
label7.setFont(new Font("Tahoma",Font.PLAIN,14));
label7.setForeground(Color.white);
pane.add(label7);

combo2 = new JComboBox(gender);
combo2.setBounds(425,200,100,20);
combo2.setForeground(Color.blue);
pane.add(combo2);

MyTable tbl = new MyTable();
inventTable=new JTable(tbl);
inventScroll1=new JScrollPane(inventTable);
inventScroll1.setBounds(10,280,500,100);
pane.add(inventScroll1);


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




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

//declare bottons


JPanel panels=new JPanel();
panels.setBounds(30,235,200,40);
panels.setBorder(new CompoundBorder(BorderFactory.createLineBorder(Color.black,1),
BorderFactory.createBevelBorder(BevelBorder.LOWERED)));
buttonstudent=new JRadioButton("Student");
buttonstaff=new JRadioButton("Staff");
radiogroup=new ButtonGroup();
radiogroup.add(buttonstudent);
radiogroup.add(buttonstaff);
panels.add(buttonstudent);
panels.add(buttonstaff);
pane.add(panels);




buttonadd = new JButton("ADD");
buttonadd.setBounds(50,520,80,30);
buttonadd.setPreferredSize(size);
buttonadd.setBorder(edge);
buttonadd.setToolTipText("click this button to add file.");
buttonadd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonadd.setFont(new Font("Arial",Font.BOLD,14));
buttonadd.setBackground(new Color(10,250,210));
buttonadd.setForeground(new Color(0,5,255));
buttonadd.setMnemonic('A');
bottompanel.add(buttonadd);

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(150,520,80,30);
buttonsave.setMnemonic('S');
bottompanel.add(buttonsave);

buttonprint = new JButton("PRINT");
buttonprint.setBounds(250,520,80,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(350,520,80,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(450,520,80,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(550,520,80,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(buttonadd);
pane.add(buttonprint);
pane.add(buttonsave);
pane.add(buttonclose);
pane.add(buttondelete);

//pane.add(buttonstudent);
//pane.add(buttonstaff);

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

class MyTable extends AbstractTableModel {
final String[] columndata={"DATE","CHARGE","CREDIT","BALANCE"};
final Object[][] data = new Object[14][6];


public Object getValueAt(int row, int col) {
return data[row][col];
}

public int getColumnCount() {
return columndata.length;
}

public int getRowCount() {
return data.length;
}

public String getColumnName(int col) {
return columndata[col];
}


/*
* Don't need to implement this method unless your table's
* editable.
*/

public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 0) {
return false;
} else {
return true;
}
}

public void setValueAt(Object value, int row, int col) {

data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println(data[row][col]);
}

}

Accession

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

public class Accession extends JFrame {

boolean inAnApplet = true;
private boolean laidOut = false;
private JPanel panel;
// private JButton Loan, b2, b3,Next,Exit;
private JLabel label, label1,label3,label4,label2;

private JTextField nameField,name,middle,last;
private JTable table;
private JScrollPane scrollPane;
private JButton Cancel, Exit,Menu,Save;
public Accession() {
Container contentPane = getContentPane();
contentPane.setLayout(null);
panel = new JPanel();
panel.setLayout( new BorderLayout() );
getContentPane().add( panel );
label1 = new JLabel("CJC High school Library System");
contentPane.add(label1);
label = new JLabel("Accession NO:");
contentPane.add(label);
label2 = new JLabel("First Name");
contentPane.add(label2);
label3= new JLabel("Last Name");
contentPane.add(label3);
label4= new JLabel("Middle Name");
contentPane.add(label4);
nameField = new JTextField(1);
contentPane.add(nameField);

String columnNames[] = { "Name", "Address", "Grade/sec"," Return Book " , "Book Title " , " Due Date" };

// Create some data
String dataValues[][] =
{
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},
{ "", "", "", "", "", ""},

};




table= new JTable(dataValues, columnNames);
scrollPane = new JScrollPane(table);
//variable.add(table);
//contentPane.add(variable);
panel.add( scrollPane, BorderLayout.CENTER );
Exit = new JButton("Exit");
contentPane.add(Exit);

Menu = new JButton("Main");
contentPane.add(Menu);
//b3 = new JButton("Inventory");
//contentPane.add(b3);
Save = new JButton("Save");
contentPane.add(Save);
Cancel= new JButton("Cancel");
contentPane.add(Cancel);
Insets insets = contentPane.getInsets();
label1.setBounds(250+insets.left,1+insets.top,300,100);
label.setBounds(100+insets.left,80+insets.top,100,30);
nameField.setBounds(200+insets.left,100+insets.top,80,20);


//main.setBounds(60+insets.left,60+insets.top,10,30);
panel.setBounds(150 + insets.left, 180 + insets.top,500,200);
Exit.setBounds(200 + insets.left, 400 + insets.top, 100, 30);
Menu.setBounds(300 + insets.left,400 + insets.top, 100,30 );
Save.setBounds(400+ insets.left,400+insets.top,100,30);
Cancel.setBounds( 500+insets.left,400+insets.top,100,30);


Menu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent l){
NoneWindow e = new NoneWindow();
e.setSize(600,600);
e.show();
}
}
);

Menu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent l){
NoneWindow e = new NoneWindow();
e.setSize(600,600);
e.show();
}
}
);


// Loan.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent l){
//Loan e = new Loan();
//e.setSize(600,600);
//e.show();
// }
// }
//);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
dispose();
} else {
System.exit(0);
}
}
});
}


public static void main(String args[]) {
Accession window = new Accession();
Insets insets = window.getInsets();
window.inAnApplet = false;

window.setTitle("ACCESSION NUMBER");
window.setSize(300 + insets.left + insets.right,
200 + insets.top + insets.bottom);
window.setVisible(true);
}
//public static void main (String args[]){
//}//
}

Valentine

import javax.swing.*;
import java.awt.*;
public class Valentine extends JFrame{
Container pane;
JButton b;
JTextField c;
public static void main(String[] args){
Valentine valdate = new Valentine();
valdate.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
valdate.setSize(400,300);
valdate.setVisible(true);
}

public Valentine(){
// ds
String[] stars = {"Robert Redford","Manilyn Monroe","Boris Karloff","Lassie","Hopalang Cassidy","Trigger","Tom Hanks","Russel Crowe","Lone Ranger","Zorro"};

String output="",Dates;
//super ("SUPER");
pane=getContentPane();
//pane.LayOut("null");
//pick the your valentine date by random
b=new JButton("OK");
b.setBounds(50,50,10,10);
pane.add(b);
//c=new JTextField(10);
//pane.add(c);
//0c.setBounds(100,100,100,100);
/*output +="Your Valentine Date is\n";
Dates = stars[(int)(stars.length*Math.random())];
output+=Dates;

JOptionPane.showMessageDialog(null,output,"Your Valentine Date is", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);*/
}
}

SpringLayout

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
import javax.swing.Spring;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;

public class TrySpringLayout{
static JFrame win = new JFrame("This is a Spring Layout");

public static void main(String[] args){
TrySpringLayout springlayout = new TrySpringLayout();
Toolkit toolkit = win.getToolkit(); //get toolkit window
Dimension wndSize = toolkit.getScreenSize(); //Get screen size

//set the position to scree center and size to half screen size
win.setBounds(wndSize.width/4, wndSize.height/4, wndSize.width/2, wndSize.height/2); //position,size
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.pack();
}

public TrySpringLayout(){
win.setVisible(true);

SpringLayout layout = new SpringLayout(); //Create a layout manager
Container content = win.getContentPane(); //Get the content pane
content.setLayout(layout);

JButton[] buttons = new JButton[6]; //Array to store buttons
for (int i=0; i< buttons.length; i++){
buttons[i] = new JButton("Press" + (i+1));
content.add(buttons[i]); //add a button to content pane
} // end for

Spring xSpring = Spring.constant(5,15,25); //x constraint for 1st button
Spring ySpring = Spring.constant(10,30,50); // y constant for first button
Spring wSpring = Spring.constant(30,80,130); // width constraint for buttons

//connect x,y for first button to left anf top of container by springs
SpringLayout.Constraints buttonConstr = layout.getConstraints(buttons[0]);
buttonConstr.setX(xSpring);
buttonConstr.setY(ySpring);

//set width and heiht of buttons and hook buttons together
for (int i=0; i buttonConstr = layout.getConstraints(buttons[i]);
buttonConstr.setHeight(ySpring); //Set the button height constraint
buttonConstr.setWidth(wSpring); // and its width constrainy

if (i>0){ // for buttons after the first
//tie W and N edges to E N of predecessor
layout.putConstraint(SpringLayout.WEST,buttons[i], xSpring,SpringLayout.EAST,buttons[i-1]);
layout.putConstraint(SpringLayout.NORTH,buttons[i], ySpring,SpringLayout.SOUTH,buttons[i-1]);
}
}

//relating the size of the window to the springs
SpringLayout.Constraints constr = layout.getConstraints(content);
constr.setConstraint(SpringLayout.EAST,Spring.sum(buttonConstr.getConstraint(SpringLayout.EAST),Spring.constant(15)));
constr.setConstraint(SpringLayout.SOUTH,Spring.sum(buttonConstr.getConstraint(SpringLayout.SOUTH),Spring.constant(10)));

}
}

GridLayoutTest

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

public class GridBagLayoutTest extends JFrame{

//main
public static void main(String[] args){
GridBagLayoutTest gridbag = new GridBagLayoutTest();
gridbag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gridbag.setSize(500,150);
gridbag.setVisible(true);
gridbag.pack();
}
//constructor
public GridBagLayoutTest(){
super("Using GridBagLayout");
buildLayout();
}
void buildLayout(){
Container pane = getContentPane();
GridBagConstraints constraints = new GridBagConstraints();
GridBagLayout layout = new GridBagLayout();
pane.setLayout(layout);

constraints.anchor = GridBagConstraints.WEST;

constraints.gridy = 0;
JLabel label = new JLabel("Firstname:");
label.setFont(new Font("Arial", Font.PLAIN,14));
pane.add(label,constraints);

JTextField textfield = new JTextField(15);
textfield.setFont(new Font("Arial",Font.PLAIN,14));
pane.add(textfield, constraints);

//add label2 and textfield2
label = new JLabel("LastName:");
label.setFont(new Font("Arial",Font.PLAIN,14));
pane.add(textfield,constraints);

//position next textfield
constraints.gridx = 0;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.fill = GridBagConstraints.HORIZONTAL;

//add spaces between horizontalfields
constraints.gridy = 1;
label = new JLabel("Address:");
label.setFont(new Font("Arial",Font.PLAIN,14));
pane.add(label,constraints);

constraints.gridx = 1;
textfield = new JTextField(30);
textfield.setFont(new Font("Arial", Font.PLAIN,14));
pane.add(textfield,constraints);

constraints.gridy++;
JButton buttonOk = new JButton("Ok");
buttonOk.setBorder(BorderFactory.createRaisedBevelBorder());
buttonOk.setBackground(Color.orange);
buttonOk.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonOk.setToolTipText("...clickable, but actionless button");
buttonOk.setFont(new Font("Lucida HandWriting", Font.BOLD,14));
pane.add(buttonOk, constraints);
}
}

ForLoop

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

public class ForLoop extends JFrame{
//cdm
String output="";
int row,col;
Container pane;
JTextArea textarea;
JPanel topPanel, bottomPanel;
//define fonts
Font tisFont = new Font("Arial", Font.PLAIN, 14);
Font PanelFont = new Font ("Tahma", Font.BOLD,15);
//format
DecimalFormat precision = new DecimalFormat("0.00000");

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

public ForLoop(){
super("Making Frames More Attractive");
//display
buildDisplay();
//topDisplay
topDisplay();
}

void buildDisplay(){
//local var
int i, starVal = 1, endVal = 50;
long square, cube;
double squareRoot, cubeRoot, pwrt = 0.3333;

pane = getContentPane();
textarea = new JTextArea (row, col);
//heading
output += "number\tsqaure\tcube\tsquare root\tcube root\n";

for (i=starVal; i <=endVal; i++){
square = i * i;
cube = i * i * 1;
squareRoot = Math.pow(i,0.5);
cubeRoot = Math.pow(i,pwrt);

output +=" " + i + "\t" + square + "\t" + cube + "\t";
output += precision.format(squareRoot) + "\t";
output += precision.format(cubeRoot) + "\t";
}

textarea.setText(output);
textarea.setFont(tisFont);
textarea.setBackground(Color.white);
textarea.setEditable(false);
textarea.setBorder(new CompoundBorder(

// BorderFactory.createLineBorder(Color.white),
BorderFactory.createBevelBorder(BevelBorder.LOWERED)));
textarea.setToolTipText(">output area<");
pane.add(textarea,BorderLayout.CENTER);
JScrollPane scrollpane = new JScrollPane(textarea);
}

void topDisplay(){
topPanel = new JPanel();
topPanel.setBackground(Color.gray);
topPanel.setToolTipText("Top Panel");
//label

JLabel label = new JLabel ("SQUARE, CUBE, AND ROOTS");
label.setFont(PanelFont);
//label.setBorder(BorderFactory.createBevelBorder(BevelBorder,RAISED));
label.setBackground(Color.red);

topPanel.add(label);
pane.add(topPanel,BorderLayout.NORTH);
}
}

Monday, April 9, 2007

FilmCast

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

public class FilmCastII extends JFrame{
//ds
Person person;
Cast filmCast = new Cast();

String output = "";
int row,col;

public static void main(String[] args){
FilmCastII theCast = new FilmCastII();
theCast.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit toolkit = theCast.getToolkit();
Dimension winSize = toolkit.getScreenSize();

//center screen
theCast.setBounds(winSize.width/4,winSize.height/4,winSize.width/2,winSize.height/2);
theCast.setVisible(true);
}

public FilmCastII(){
//window title
super("THE CAST FOR THE FILM");

//populate the crowd
for(;;){
person = readPerson();
if (person == null){
break;
}

filmCast.add(person);
}

int count = filmCast.size();
output += "You've added"+count+(count==1?"person":"people")+"to the film cast.\n";

//show the members of the cast
Iterator thisLot = filmCast.iterator();

output += "\nCasted in the Film are:\n";

//display the people in the cast
while (thisLot.hasNext()){
output+=(thisLot.next())+"\n";
}

//display output
Container pane = getContentPane();
JTextArea textarea = new JTextArea(row,col);

textarea.setText(output);
textarea.setFont(new Font("Tahoma",Font.PLAIN,14));
textarea.setBackground(new Color(250,250,0));

pane.add(textarea);

//add bottom panel
//pane.add(new BottomPanel(), BorderLayout.SOUTH);
}

//readPerson method
//enter person from keyboard
static public Person readPerson(){

//read in the first name
String fullName = JOptionPane.showInputDialog(null,
"\nPlease enter fullname of the actor and actress\n"+
"format: familyname, firstname \nor enter ! to end.|n",
"INPUT FULLNAME OF STAR",JOptionPane.QUESTION_MESSAGE);

fullName = fullName.trim();

if(fullName.charAt(0) == '!'){
return null;
}

//check if format is correct
char separator = ',';
int index = 0, endIndex = 0;
String firstname,surname;

//extract firstname and Lastname of actor/actress
endIndex = fullName.indexOf(separator,index);
surname = fullName.substring(0,endIndex);
firstname = fullName.substring(endIndex + 1, fullName.length());

return new Person(firstname,surname);
}

CalendarFormat

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

public class CalendarFormat extends JFrame{

//cdm
private static JFrame winframe = new JFrame();

Container pane;
JTextArea textarea;

int row, col;

String output="";

public static void main(String[] args){
CalendarFormat formatdate = new CalendarFormat();
formatdate.setBounds(150,150,300,220);
formatdate.setVisible(true);
}
public CalendarFormat(){

super ("Date Utility");

//container
pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.setBackground(new Color(5,255,30));
pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

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

//window listener
addWindowListener(new WindowHandler());

//output display
outputDisplay();
}

void outputDisplay(){

//local var
int year, month, day;
Date date = new Date();
output+="Today is:"+date.toString()+"\n";
//calendar class
GregorianCalendar today = new GregorianCalendar();

year = today.get(today.YEAR);
month = today.get(today.MONTH);
day = today.get(today.DATE);

output += "\n\nYEAR:"+year+"\n";
output += "MONTH:"+(month +1)+"\n";
output += "DAY:"+day+"\n";


textarea.setText(output);
textarea.setFont(new Font("Tahoma",Font.PLAIN,14));
textarea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
pane.add(textarea);

}

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