Anda di halaman 1dari 32

JAVA LAB MANUAL

II Year B.Tech CSE-II Semester

MVGRCE ,DEPT OF CSE


Preface

Java is related to C++, which is a direct descendent of C. Much of the character of


java is inherited from these two languages. From C, java derives its syntax. Many of
java’s object-oriented features were influenced by C++.

Object-oriented programming (OOP) is at the core of Java. In fact, all java


programs are to at least some extent object-oriented. OOP is so integral to java that it is
best to understand its basic principles. In this manual include material that serves as a
review of basics Java.

Next section covers basic concepts programs like quadratic equation, Fibonacci
series.

Next section covers method overloading, inheritance, polymorphism, how to


reads a file and displays a file and displays the file on the screen.

Next section covers how to implement stack ADT and to convert infix expression
into Postfix form.

Next section covers how to handle mouse events and threads.

MVGRCE ,DEPT OF CSE


Syllabus

1. Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c
= 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative,
display a message stating that there are no real solutions.
2. The Fibonacci sequence is defined by the following rule. The fist two values in the
sequence are 1and 1. Every subsequent value is the run of the two values preceding it.
Write a Java program that uses both recursive and non recursive functions to print the nth
value in the Fibonacci sequence.
3. Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that Integer.
4. Write a Java program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome.
5. Write a Java program for sorting a given list of names in ascending order.
6. Write a Java program to multiply two given matrices.
7. Write a Java Program that reads a line of integers, and then displays each integers, and
the sum of all the integers (use stringTokenizer class)
8. Write a Java program that reads on file name from the user then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the
type of file and the length of the file in bytes.
9. Write a Java program that reads a file and displays a file and displays the file on the
screen, with a line number before each line.
10. Write a Java program that displays the number of characters, lines and words in a text
file.
11. Write a Java program that:
a) Implements stack ADT. b) Converts infix expression into Postfix form.
12. Write an applet that displays a simple message.
13. Write an applet that computes the payment of a loan based on the amount of the loan,
the interest
rate and the number of months. It takes one parameter from the browser: Monthly rate; if
true, the interest rate is per month; Other wise the interest rate is annual.
14. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the + - X % operations. Add a text field to display the result.
15. Write a Java program for handling mouse events.
16. Write a Java program for creating multiple threads
17. Write a Java program that correctly implements producer consumer problem using
the concept of inter thread communication.
18. Write a Java program that lets users create Pie charts. Design your own user interface
(with swings& AWT)
19. Write a Java program that allows the user to draw lines, rectangles and OU.als.

MVGRCE ,DEPT OF CSE


20. Write a Java program that implements a simple client/server application. The client
sends data to
a server. The server receives the data, uses it to produce a result, and then sends the result
back
to the client. The client displays the result on the console. For ex: The data sent from the
client is
the radius of a circle, and the result produced by the server is the area of the circle.

Program:1

REFERENCE PROGRAM TO IMPLEMENT METHOD OVERLOADING

// class with methods to square integer and float


class A

MVGRCE ,DEPT OF CSE


{
// square method with int argument
public int square( int intValue )
{
System.out.println( "Called square with int argument: " + intValue );
return intValue * intValue;
} // end method square with int argument

// square method with double argument

public double square( double doubleValue )


{
System.out.println( "Called square with double argument: " + doubleValue );
return doubleValue * doubleValue;
} // end method square with double argument

} // end class A

public class MethodOverload

{
public static void main(String[] args)
{
A a=new A();
System.out.println( "The square of integer 7 is " + a.square( 7 ) + "\nThe
square of double 7.5 is " + a.square( 7.5 ) );
}
}

Sample Output:

Called square with int argument: 7


Called square with double argument: 7.5

The square of integer 7 is 49


The square of double 7.5 is 56.25

MVGRCE ,DEPT OF CSE


Program:2

REFERENCE PROGRAM TO FIND FACTORIAL OF A NUMBER

// Fact.java

class Fact
{
private int x;
public fact(int n)
{
x=n;
}
public int calfac()
{
int f=1;
for(int i=x;i>0;i--)
{
f=f*i;
}
return f;
}
}

// Factorial.java

class Factorial
{
public static void main(String[] args)
{
Fact p=new Fact(5);
int res=p.calfac();
System.out.println("Factorial of "+p.x+" is "+res);

}
}

To execute the above program, the Fact.java should be compiled first as Factorial.java is
trying to create object of the above class.

When compiling the second module, the compiler will return an error as the private
variable of the class is not accessible beyond the class. In order to access the private
variable, the class should have a public method.

MVGRCE ,DEPT OF CSE


A modified version of the above program, which has a public print method that displays
the result, is given below. The program also contains documentation comments that are
used while writing a program to generate html documentation for easy reference.

/** Class that has a constructor and two methods for calculating factorial
*/

class Fact
{
private int x;

/**
* Constructor to initialize
* @param n the number for which factorial is to be found
*/
public Fact(int n)
{
x=n;
}

/**
* Method to calculate the factorial
* @return f the factorial of the number
*/
public int calfac()
{
int f=1;
for(int i=x;i>0;i--)
{
f=f*i;
}
return f;
}

/**
* Method to display the result
* @param n the factorial
*/
public void print(int r)
{
System.out.println("Factorial of "+this.x+" is "+r);

}
/**
* The class that accesses the Fact class and creates an object

MVGRCE ,DEPT OF CSE


*/

class Fact
{
public static void main(String[] args)
{
System.out.println(“ Execution: java Factorial [number]“);
int x= Integer.parseInt(args[0]);
Fact p=new Fact(x);
int res=p.calfac();
p.print(res);
}
}

Compilation:
C:\javac Fact.java
C:\javac Factorial.java

Interpretation:
C:\java Factorial 8

Sample Output:
Execution: java Factorial [number]
Factorial of 8 is 40320

Documentation:
C:\javadoc Fact.java
C:\javadoc Factorial.java

The generated Documentation for Fact.java:


Class Fact
java.lang.Object
Fact
public class Fact
extends java.lang.Object

Class that has a constructor and two methods for calculating factorial

Constructor Summary
Fact(int n)
Constructor to initialize

MVGRCE ,DEPT OF CSE


Method Summary
int calfac()
Method to calculate the factorial
void print(int r)
Method to display the result

Constructor Detail
Fact
public Fact(int n)
Constructor to initialize
Parameters:
n - the number for which factorial is to be found

Method Detail
calfac
public int calfac()
Method to calculate the factorial
Returns:
f the factorial of the number

print

public void print(int r)


Method to display the result
Parameters:
r - the factorial

MVGRCE ,DEPT OF CSE


Program:3

REFERENCE PROGRAM TO IMPLEMENT MULTI-LEVEL INHERITANCE

class A
{
int a;
public A(int m)
{
a=m;
System.out.println("super class variable "+this.a);
}
}
class B extends A
{
double b;
public B(int m,double n)
{
super(m);
b=n;
System.out.println("sub class, variables"+this.b+" "+super.a);
}
}
class C extends B
{
char c;
public C2(int m, double n, char ch)
{
super(m,n);
c=ch;
System.out.println("sub-sub class, variables "+this.c+"
"+super.b+""+super.a);
}
}

public class Inheritance


{
public static void main(String[] args)
{
A2 p=new A2(10);
B2 q=new B2(20,3.5);
C2 r=new C2(30,4.5,'h');
}
}

MVGRCE ,DEPT OF CSE


Sample Output:

super class, variables10


super class, variables20
sub class, variables3.5 20
super class, variables30
sub class, variables4.5 30
sub-sub class, variables h 4.530

Note:

In Java Multi-level inheritance is allowed, but multiple inheritance is not allowed.


i.e. one class cannot extend multiple classes at the same time. Java provides an excellent
mechanism for multiple inheritance using Interface. One class can implement multiple
interfaces, each of which contains method signatures. The class which implements the
interface should override the methods defined in the interface, and give the detailed
implementation of each method.

// interface1 which provides method signature

public interface Test


{
int print(int x);
}
//interface 2
public interface Test1
{
void disp();
}

// class which implements two interfaces


class IfaceEx implements Test, Test1
{
public int print(int y)
{
System.out.println("y= "+y);
return y*2;
}
void disp()
{
System.out.println("sample display");
}
}
// this class can have its own additional methods.

MVGRCE ,DEPT OF CSE


Program:4

REFERENCE PROGRAM TO MAKE USE OF ARRAY METHODS

class Array
{
public static void main(String[] args)
{
int[] data=new int[10];

for(int i=0;i<data.length;i++)
data[i]=i+1;
System.out.println("elements of data ");

for(int i=0;i<data.length;i++)
System.out.print(" "+data[i]);

int[] prices=data.clone();

System.out.println("\nelements of prices ");

for(int i=0;i<prices.length;i++)
System.out.print(" "+prices[i]);

int[] copy=new int[10];

System.out.println("\nelements copied ");


System.arraycopy(data,2,copy,1,5);

for(int i=0;i<copy.length;i++)
System.out.print(" "+copy[i]);

}
}

Sample output:

elements of data
1 2 3 4 5 6 7 8 9 10
elements of prices
1 2 3 4 5 6 7 8 9 10
elements copied
0 3 4 5 6 7 0 0 0 0

MVGRCE ,DEPT OF CSE


Program:5

REFERENCE PROGRAM TO MAKE USE OF ARRAYLIST IN CREATING


BANK ACCOUNTS

import java.util.ArrayList;
class BankAcc
{
private double bal;
public BankAcc()
{
bal=0;
}
public BankAcc(double inbal )
{
bal=inbal;
}
public void deposit(double am)
{
bal=bal+am;
}
public void withdraw(double am)
{
bal-=am;
}
public double getbal()
{
return bal;
}
}
class BankAccount1
{
public static void main(String[] arr)
{
ArrayList<BankAcc> accounts=new ArrayList<BankAcc>();

accounts.add(new BankAcc(1000));
accounts.add(new BankAcc(2000));

System.out.println("Initial Accounts");

for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());

MVGRCE ,DEPT OF CSE


BankAcc samp1=new BankAcc(5670);
samp1.deposit(1000);
accounts.add(1,samp1);
accounts.remove(0);

BankAcc nuacc=new BankAcc(5000);


nuacc.withdraw(1000);
accounts.set(1,nuacc);

System.out.println("Accounts After Modification");

for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());

int n=accounts.size();

BankAcc samp=accounts.get(0);
System.out.println("balance in first account: "+samp.getbal());

for(BankAcc e:accounts)
System.out.println("balance: "+e.getbal());
}
}

Sample output:

Initial Accounts
balance: 1000.0
balance: 2000.0
Accounts After Modification
balance: 6670.0
balance: 4000.0
balance in first account: 6670.0
balance: 6670.0
balance: 4000.0

MVGRCE ,DEPT OF CSE


Program:6

REFERENCE PROGRAM TO DEMONSTRATE TRY-CATCH-FINALLY IN


EXCEPTION HANDLING

public class Exceptions


{
public static void main( String args[] )
{
try
{
throwException(); // call method throwException
}
// catch Exceptions thrown by method throwException
catch ( Exception exception )
{
System.out.println( "Exception handled in main" );
}
doesNotThrowException();
}

// demonstrate try/catch/finally
public static void throwException() throws Exception
{
// throw an exception and immediately catch it
try
{
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
// catch exception thrown in try block
catch ( Exception exception )
{
System.out.println("Exception handled in method
throwException");
throw exception; // rethrow for further processing
// any code here would not be reached
}

// this block executes regardless of what occurs in try/catch


finally
{
System.out.println( "Finally executed in throwException" );
}
// any code here would not be reached
} // end method throwException

MVGRCE ,DEPT OF CSE


// demonstrate finally when no exception occurs
public static void doesNotThrowException()
{
// try block does not throw an exception
try
{
System.out.println( "Method doesNotThrowException" );
}
// catch does not execute, because no exception thrown
catch( Exception exception )
{
System.out.println( exception );
}
// this clause executes regardless of what occurs in try/catch
finally
{
System.out.println("Finally executed in doesNotThrowException" );
}
System.out.println( "End of method doesNotThrowException" );

} // end method doesNotThrowException


} // end class Exceptions

Sample Output:

Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException

MVGRCE ,DEPT OF CSE


Program 7:

REFERENCE PROGRAM TO RUN THREADS WITH PRIORITIES

import java.lang.Thread;

public class A extends Thread


{
public void run()
{
char p[]={‘c’,’o’,’m’,’p’,’u’,’t,’e’,’r’};
for(int i=0;i<=7;i++)
System.out.println(“threadA: “+p[i]);
try{
Thread.sleep(1000);
}
catch(Exception e)
{System.out.prinntln(e.printStackTrace(););
}
System.out.println(“End of threadA”);
}
}

public class B extends Thread


{
public void run()
{
char p[]={‘s’,’c’,’i’,’e’,’n’,’c’,’e’};

for(int i=0;i<7;i++)
System.out.println(“ThreadB :”+p[i]);

try
{
Thread.sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(“End of threadB”);
}
}

MVGRCE ,DEPT OF CSE


class PriorityThread
{
public static void main(String s[])
{
A a=new A();
B b=new B();

b.setPriority(Thread.MIN_PRIORITY);
a.setPriority(Thread.NORM_PRIORITY);

b.start();
a.start();

System.out.println(“End of main thread”);


}
}

Sample Output:

End of Main Thread


Thread B :s
Thread A: c
Thread B :c
Thread A: o
Thread A: m
Thread A: p
Thread A: u
Thread A: t
Thread A: e
Thread A: r
Thread B :i
Thread B :e
Thread B :n
Thread B :c
Thread B :e
End of Thread B
End of Thread A

MVGRCE ,DEPT OF CSE


Program: 8

REFERENCE PROGRAM TO HANDLE KEY EVENTS

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*
<applet code=KeyEvents width=300 height=100> </applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
String msg=" ";
int X=10,Y=20;

public void init()


{
addKeyListener(this);
requestFocus();
}

public void keyPressed(KeyEvent ke)


{
showStatus("Key Down");
int key=ke.getKeyCode();

if(key==KeyEvent.VK_LEFT)
{
msg+="<Left Arrow>";
repaint();
}

if(key==KeyEvent.VK_RIGHT)
{
msg+="<Right Arrow>";
repaint();
}

if(key==KeyEvent.VK_CAPS_LOCK)
{
msg+="<Caps Lock is On>";
repaint();
}

MVGRCE ,DEPT OF CSE


}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg+=ke.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,X,Y);
}
}

MVGRCE ,DEPT OF CSE


Program: 9

REFERENCE PROGRAM TO USE MANUAL LAYOUT IN AN APPLET

import java.applet.*;
import java.awt.*;
/*
<applet code=ManualLayout width=100 height=100>
</applet>
*/
public class ManualLayout extends Applet
{
Button b;
TextField tf;
public void init()
{
b=new Button("ok");
add(b);
tf=new TextField(“”,20);
}
public void paint(Graphics g)
{
setLayout(null);
b.setLocation(25,30);
b.setSize(30,40);
tf.setLocation(20,80);
}
}

This shows the usage of manual layout which does not change the size of components in
scale to the size of applet.

MVGRCE ,DEPT OF CSE


Program6:

REFERENCE PROGRAM WHICH IMPLEMENTS ADJUSTMENT LISTENER

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=ColorEx width=300 height=300> </applet>
*/
public class ColorEx extends Applet implements AdjustmentListener
{
Scrollbar red,blue,green;
Color c;

public void init()


{
red=new Scrollbar(Scrollbar.VERTICAL,0,1,0,255);
blue=new Scrollbar(Scrollbar.VERTICAL,0,1,0,255);
green=new Scrollbar(Scrollbar.VERTICAL,0,1,0,255);

add(red);
add(blue);
add(green);

red.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
green.addAdjustmentListener(this);

public void adjustmentValueChanged(AdjustmentEvent ae)


{
int r=red.getValue();
int b=blue.getValue();
int g=green.getValue();

c=new Color(r,g,b);
repaint();
}

public void paint(Graphics g)


{
setBackground(c);
g.setColor(Color.white);
Font f=new Font("Courier",Font.BOLD,20);

MVGRCE ,DEPT OF CSE


g.setFont(f);
g.drawString(c.toString(),50,80);
}
}

MVGRCE ,DEPT OF CSE


Program: 10

REFERENCE PROGRAM TO USE TABBED PANES FOR MULTIPLE


CONTAINERS
import javax.swing.*;
/*
<applet code=JTabbedPaneDemo width=400 height=100> </applet>
*/
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
JTabbedPane jtp=new JTabbedPane();
jtp.add("Flowers",new FlowersPanel());
jtp.add("Fruits",new FruitsPanel());
jtp.add("Nuts",new NutsPanel());
getContentPane().add(jtp);
}
}

class FlowersPanel extends JPanel


{
public FlowersPanel()
{
JButton b1=new JButton("Rose");
add(b1);
JButton b2=new JButton("Jasmine");
add(b2);
JButton b3=new JButton("Lotus");
add(b3);
}
}

class FruitsPanel extends JPanel


{
public FruitsPanel()
{
JCheckBox cb1=new JCheckBox("Mango");
add(cb1);
JCheckBox cb2=new JCheckBox("Apple");
add(cb2);
JCheckBox cb3=new JCheckBox("Banana");
add(cb3);
}
}

MVGRCE ,DEPT OF CSE


class NutsPanel extends JPanel
{
public NutsPanel()
{
JComboBox jcb=new JComboBox();
jcb.addItem("Date");
jcb.addItem("Cashew");
jcb.addItem("Badam");
add(jcb);
}
}

MVGRCE ,DEPT OF CSE


Program: 11

REFERENCE PROGRAM TO DRAW LINES, OVALS AND RECTANGLES

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

public class LinesRectsOvals extends JFrame {

// set window's title bar String and dimensions


public LinesRectsOvals()
{
super( "Drawing lines, rectangles and ovals" );
setSize( 400, 165 );
setVisible( true );
}

// display various lines, rectangles and ovals

public void paint( Graphics g )


{
super.paint( g ); // call superclass's paint method

g.setColor( Color.RED );
g.drawLine( 5, 30, 350, 30 );

g.setColor( Color.BLUE );
g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );

g.setColor( Color.CYAN );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );

g.setColor( Color.YELLOW );
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false );

g.setColor( Color.MAGENTA );
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );

} // end method paint

MVGRCE ,DEPT OF CSE


// execute application
public static void main( String args[] )
{
LinesRectsOvals application = new LinesRectsOvals();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class LinesRectsOvals

MVGRCE ,DEPT OF CSE


Program : 12

REFERENCE PROGRAM TO DISPLAY AN ANALOG CLOCK

import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;
/*
<applet code=Clock width=200 height=200> </applet>
*/
public class Clock extends Applet implements Runnable {
private volatile Thread timer; // The thread that displays clock
private int lastxs, lastys, lastxm, lastym, lastxh, lastyh; // Dimensions to draw hands
private SimpleDateFormat formatter; // Formats the date displayed
private String lastdate; // String to hold date displayed
private Font clockFaceFont; // Font for number display on clock
private Date currentDate; // Used to get date to display
private Color handColor; // Color of main hands and dial
private Color numberColor; // Color of second hand and numbers
private int xcenter = 80, ycenter = 55; // Center position

public void init() {


int x,y;
lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0;
formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy",
Locale.getDefault());
currentDate = new Date();
lastdate = formatter.format(currentDate);
clockFaceFont = new Font("Serif", Font.PLAIN, 14);
handColor = Color.blue;
numberColor = Color.darkGray;

try
{
setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16)));
}
catch (NullPointerException e) { }
catch (NumberFormatException e) { }
try
{
handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16));
}
catch (NullPointerException e) { }
catch (NumberFormatException e) { }

MVGRCE ,DEPT OF CSE


try
{
numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"), 16));
}
catch (NullPointerException e) { }
catch (NumberFormatException e) { }
resize(300,300); // Set clock window size
}

// Paint is the main part of the program


public void update(Graphics g) {
int xh, yh, xm, ym, xs, ys;
int s = 0, m = 10, h = 10;
String today;

currentDate = new Date();

formatter.applyPattern("s");
try
{
s = Integer.parseInt(formatter.format(currentDate));
}
catch (NumberFormatException n) {
s = 0;
}
formatter.applyPattern("m");
try
{
m = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
m = 10;
}
formatter.applyPattern("h");
try {
h = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
h = 10;
}

// Set position of the ends of the hands


xs = (int) (Math.cos(s * Math.PI / 30 - Math.PI / 2) * 45 + xcenter);
ys = (int) (Math.sin(s * Math.PI / 30 - Math.PI / 2) * 45 + ycenter);
xm = (int) (Math.cos(m * Math.PI / 30 - Math.PI / 2) * 40 + xcenter);
ym = (int) (Math.sin(m * Math.PI / 30 - Math.PI / 2) * 40 + ycenter);
xh = (int) (Math.cos((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 + xcenter);
yh = (int) (Math.sin((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 + ycenter);

MVGRCE ,DEPT OF CSE


// Get the date to print at the bottom
formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy");
today = formatter.format(currentDate);

g.setFont(clockFaceFont);
// Erase if necessary
g.setColor(getBackground());
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym);
}
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
}

// Draw date and hands


g.setColor(numberColor);
g.drawString(today, 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(handColor);
g.drawLine(xcenter, ycenter-1, xm, ym);
g.drawLine(xcenter-1, ycenter, xm, ym);
g.drawLine(xcenter, ycenter-1, xh, yh);
g.drawLine(xcenter-1, ycenter, xh, yh);
lastxs = xs; lastys = ys;
lastxm = xm; lastym = ym;
lastxh = xh; lastyh = yh;
lastdate = today;
currentDate = null;
}

public void paint(Graphics g) {


g.setFont(clockFaceFont);
// Draw the circle and numbers
g.setColor(handColor);
g.drawArc(xcenter-50, ycenter-50, 100, 100, 0, 360);
g.setColor(numberColor);
g.drawString("9", xcenter-45, ycenter+3);
g.drawString("3", xcenter+40, ycenter+3);
g.drawString("12", xcenter-5, ycenter-37);
g.drawString("6", xcenter-3, ycenter+45);

MVGRCE ,DEPT OF CSE


// Draw date and hands
g.setColor(numberColor);
g.drawString(lastdate, 5, 125);
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.setColor(handColor);
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym);
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
}

public void start() {


timer = new Thread(this);
timer.start();
}

public void stop() {


timer = null;
}

public void run() {


Thread me = Thread.currentThread();
while (timer == me) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
}
repaint();
}
}
public String getAppletInfo() {
return "Title: An analog clock."; }

public String[][] getParameterInfo() {


String[][] info = {
{"bgcolor", "hexadecimal RGB number",
"The background color. Default is the color of your browser."},
{"fgcolor1", "hexadecimal RGB number",
"The color of the hands and dial. Default is blue."},
{"fgcolor2", "hexadecimal RGB number",
"The color of the second hand and numbers. Default is dark gray."}
};
return info;
}
}

MVGRCE ,DEPT OF CSE


MVGRCE ,DEPT OF CSE

Anda mungkin juga menyukai