Assignment of JAVA: Submitted To: Submitted by
Assignment of JAVA: Submitted To: Submitted by
Q1. Write a program that demonstrates the various stages through which an
applet undergoes during its life-cycle.
ANS
\/*
Applet Life Cycle Example
This java example explains the life cycle of Java applet.
*/
import java.applet.Applet;
import java.awt.Graphics;
/*
*
* Applet can either run by browser or appletviewer application.
* Define <applet> tag within comments as given below to speed up
* the testing.
*/
/*
<applet code="AppletLifeCycleExample" width=100 height=100>
</applet>
*/
/*
* init method is called first.
* It is used to initialize variables and called only once.
*/
public void init() {
super.init();
}
/*
* start method is the second method to be called. start method is
* called every time the applet has been stopped.
*/
public void start() {
super.start();
}
/*
* stop method is called when the the user navigates away from
* html page containing the applet.
*/
public void stop() {
super.stop();
}
/*
* destroy method is called when browser completely removes
* the applet from memeory. It should free any resources initialized
* during the init method.
*/
public void destroy() {
super.destroy();
}
Q2. Write a java program to copy the contents of one file to another.
ANS import java.io.*;
Q3. Design a GUI program that gets from its user a person’s date of birth and
thus tell him his/her zodiac sign. Make use of events handled from keyboard.
ANS
import javax.swing.*;
public class Zodiac extends JPanel {
ImageIcon icon;
Zodiac(){
String[] s=JOptionPane.showInputDialog
("MM/DD/YYYY").split("/");
int m=Integer.parseInt(s[0]);
int d=Integer.parseInt(s[1]);
if(m==1 & d<21){
icon=createImageIcon
("Capricorn.PNG");
}
add(new JLabel(icon));
}
public static void main(String args[]){
JFrame f=new JFrame("Zodiacs");
f.setDefaultCloseOperation(
JFrame.
EXIT_ON_CLOSE);
f.add(new Zodiac());
f.pack();
f.setVisible(true);
}
Q4. Can you write a Java class that could be used both as an applet as well as
an application? Explain how?
ANS Applications and applets have much of the similarity such as both have most of the same features
and share the same resources. Applets are created by extending the java.applet.Applet class while the java
applications start execution from the main method. Applications are not too small to embed into a html page
so that the user can view the application in your browser. On the other hand applet have the accessibility
criteria of the resources. The key feature is that while they have so many differences but both can perform
the same purpose.
import java.awt.*;
import javax.swing.*;
//============================================================ main
public static void main(String[] args) {
//... Create an initialize the applet.
JApplet theApplet = new SampleApplet();
//theApplet.init(); // Needed if overridden in applet
//theApplet.start(); // Needed if overridden in applet
//... Create a window (JFrame) and make applet the content pane.
JFrame window = new JFrame("Sample Applet and Application");
window.setContentPane(theApplet);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack(); // Arrange the components.
//System.out.println(theApplet.getSize());
window.setVisible(true); // Make the window visible.
}
//=============================================== Applet constructor
public SampleApplet() {
add(new JLabel("This is both an Applet and Application!"));
}
}
Q5. With a program example, illustrate the difference between paint() and
repaint() methods.
ANS Paint():- The paint() method is called automatically whenever the window needs to be refreshed.
The programmer never calls paint() .
repaint():-Programmer calls repaint() in order to obtain a rendering.
repaint() then again call paint() to service repaint() method.
Thus the paint() method conjuction with update() method makes repaint();
Paint is called for the first time the applet is loaded whereas repaint method is called everytime the applet is
refreshed.
The paint() method is called by the core to paint a component. It passes to the paint method a Graphic
handler to use the actually do the painting
The repaint() method is used to transmit to the core "please call my paint method with the correct graphic
handler"
public void paint(Graphics g) {
// Dynamically calculate size information
Dimension size = getSize();
// diameter
int d = Math.min(size.width, size.height);
int x = (size.width - d)/2;
int y = (size.height - d)/2;
Q6. Design an applet that shows a colorful face and a marquee of your
particulars like name, height, age etc.
ANS import java.applet.*;
import java.awt.*;
import java.net.*;
class Message {
String text, link;
int x, width;
}
public class Marquee extends Applet implements Runnable {
initMessageSettings();
initMessages();
initMessagePositions();
thread.start();
}
moveMessages();
}
catch(InterruptedException e) {
}
}
}
if(errorMsg != null) {
displayError(gDraw);
g.drawImage(drawBuffer, 0, 0, null);
return;
}
int y;
if(Messages[i].link == null) {
gDraw.setColor(textColor);
gDraw.setFont(textFont);
y = getCenteredY(textFontMetrics);
} else {
if(mousePos != -1) {
// If the mouse is on the link...
if(mousePos >= Messages[i].x && mousePos < Messages[i].x + Messages[i].width) {
mouseLink = Messages[i].link;
gDraw.setColor(activeColor);
} else
gDraw.setColor(linkColor);
} else
gDraw.setColor(linkColor);
gDraw.setFont(linkFont);
y = getCenteredY(linkFontMetrics);
}
g.drawImage(drawBuffer, 0, 0, null);
//
// Information functions
//
return info;
}
//
// Mouse operations
//
try {
if(mouseLink != null) {
URL url = new URL(mouseLink);
ac.showDocument(url);
}
}
catch(MalformedURLException e) {
}
return true;
}
//
// Parameter initialization functions
//
if(s != null)
defColor = new Color(Integer.parseInt(s, 16));
}
catch(Exception e) { }
return defColor;
}
// Parse values
String fontFace = defFont.getName(), fontStyles;
int fontStyle = Font.PLAIN, fontSize = defFont.getSize();
if(delim1 > 0)
// Get the font typeface
fontFace = s.substring(0, delim1);
if(fontStyles.indexOf('B') != -1)
fontStyle |= Font.BOLD;
if(fontStyles.indexOf('I') != -1)
fontStyle |= Font.ITALIC;
}
try {
// Get the scroll amount
if((s = getParameter("scrollamount")) != null) {
err = "Invalid scroll amount";
scrollAmount = Integer.parseInt(s);
if(scrollAmount < 1)
scrollAmount = 1;
if(scrollAmount > size.width)
scrollAmount = size.width;
}
if(text == null) {
numMessages = i;
return;
}
if(text.compareTo("\u00A0") == 0) {
Messages[i].text = "";
Messages[i].link = null;
Messages[i].width = size.width;
} else {
Messages[i].text = text;
Messages[i].link = getParameter("link" + paramNum);
if(Messages[i].link == null)
Messages[i].width = textFontMetrics.stringWidth(text);
else {
if(!Messages[i].link.startsWith("http:"))
Messages[i].link = linkBase + Messages[i].link;
Messages[i].width = linkFontMetrics.stringWidth(text);
}
}
}
}
//
// Helper functions
//
g.drawString(errorMsg,
getCenteredX(errorMsg, textFontMetrics),
getCenteredY(textFontMetrics));
}
// Move messages
private void moveMessages() {
for(int i = 0; i < numMessages; i++)
Messages[i].x -= scrollAmount;
}
}
Q7. Can you pass parameters in an applet? If yes, illustrate with program
example.
ANSimport java.awt.*;
import java.applet.*;
public class ParameterExample extends Applet
{
// We'll save the first HTM parameter as a String
String parameter1;
// the second one we will use as an integer
int parameter2;
// third one too
int parameter3;
// we'll add param2 to param2
int result;
public void init()
{
// This method will get the specified parameter's value
// out of the HTML code that is calling the applet.
parameter1 = getParameter("param1");
parameter2 = Integer.parseInt(getParameter("param2"));
parameter3 = Integer.parseInt(getParameter("param3"));
result = parameter2 + parameter3;
}
/* This only works when those paramters are actually in the HTML code.
That code for this example is :
<APPLET CODE="ParameterExample" WIDTH=200 HEIGHT=100>
<param name="param1" value="Hello">
<param name="param2" value="14">
<param name="param3" value="2">
</APPLET>