assignment 4 java

Upload: harish-upmanyu

Post on 08-Apr-2018

247 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/7/2019 assignment 4 java

    1/16

    Assignment of JAVA

    Submitted to: Submitted by:

    Mr. Rakesh Verma Karan Madan

    B.Tech-

    MBA-IT

    RK27B1A26

    Roll no. 26

    3470070039

  • 8/7/2019 assignment 4 java

    2/16

    PART A

    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 tag within comments as given below to speed up

    * the testing.*/

    /*

    */

    public class AppletLifeCycleExample extends 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();

    }

    /*

  • 8/7/2019 assignment 4 java

    3/16

    * stop method is called when the the user navigates away from

    * html page containing the applet.

    */

    public void stop() {

    super.stop();

    }

    /* paint method is called every time applet has to redraw its

    * output.

    */

    public void paint(Graphics g) {

    super.paint(g);

    }

    /*

    * 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.*;public class CopyFile{private static void copyfile(String srFile, String dtFile){

    try{

    File f1 = new File(srFile);

    File f2 = new File(dtFile);

    InputStream in = new FileInputStream(f1);

    //For Append the file.

    // OutputStream out = new FileOutputStream(f2,true);

    //For Overwrite the file.

    OutputStream out = new FileOutputStream(f2);

    byte[] buf = new byte[1024];

    int len;

    while ((len = in.read(buf)) > 0){

    out.write(buf, 0, len);

    }

  • 8/7/2019 assignment 4 java

    4/16

    in.close();

    out.close();

    System.out.println("File copied.");

    }

    catch(FileNotFoundException ex){

    System.out.println(ex.getMessage() + " in the specified directory.");

    System.exit(0);

    }

    catch(IOException e){

    System.out.println(e.getMessage());

    }

    }

    public static void main(String[] args){

    switch(args.length){

    case 0: System.out.println("File has not mentioned.");

    System.exit(0);

    case 1: System.out.println("Destination file has not mentioned.");

    System.exit(0);

    case 2: copyfile(args[0],args[1]);

    System.exit(0);

    default : System.out.println("Multiple files are not allow.");System.exit(0);

    }

    }

    }

    Q3. Design a GUI program that gets from its user a persons date of birth and

    thus tell him his/her zodiac sign. Make use of events handled from keyboard.

    ANSimport 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

  • 8/7/2019 assignment 4 java

    5/16

    f.add(new Zodiac());

    f.pack();

    f.setVisible(true);

    }

    private ImageIcon createImageIcon(String path) {

    System.out.println("creating imgs "+path);

    java.net.URL imgURL = getClass().getResource(path);

    if (imgURL != null) {

    return new ImageIcon(imgURL);

    } else {

    System.out.println(imgURL);

    System.err.println("Couldn't find file: " + path);

    return null;

    }

    }

    }

    PART B

    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 featuresand 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.*;

    public class SampleApplet extends JApplet {

    //============================================================ 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.

    }

  • 8/7/2019 assignment 4 java

    6/16

    //=============================================== Applet constructor

    public SampleApplet() {

    add(new JLabel("This is both an Applet and Application!"));

    }

    }

    Q5. With a program example, illustrate the difference between paint() andrepaint() 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;

    // draw circle (color already set to foreground)

    g.fillOval(x, y, d, d);

    g.setColor(Color.black);

    g.drawOval(x, y, d, d);

    }

    MouseListener l = new MouseAdapter() {

    public void mousePressed(MouseEvent e) {

    MyButton b = (MyButton)e.getSource();

    b.setSelected(true);

    b.repaint();}

    public void mouseReleased(MouseEvent e) {

    MyButton b = (MyButton)e.getSource();

    b.setSelected(false);

    b.repaint();

    }

  • 8/7/2019 assignment 4 java

    7/16

    }

    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 {

    Thread thread = new Thread(this);

    private Dimension size;private Color backColor, textColor, linkColor, activeColor;

    private Font textFont, linkFont;

    private FontMetrics textFontMetrics, linkFontMetrics;

    private String linkBase;

    private final int maxMessages = 50;

    private int numMessages = 0, scrollAmount = 1, scrollDelay = 25;

    private Message Messages[];

    private int firstMessage = 0;

    private int mousePos = -1;

    private String mouseLink;

    private String errorMsg;

    public void init() {

    // Save the applet size

    size = size();

    // Get applet parameter settings

    backColor = initColor("bgcolor", Color.black);

    setBackground(backColor);

    textColor = initColor("text", Color.lightGray);

    linkColor = initColor("link", Color.yellow);

    activeColor = initColor("alink", Color.red);

  • 8/7/2019 assignment 4 java

    8/16

    textFont = initFont("textfont", getFont());

    textFontMetrics = getFontMetrics(textFont);

    linkFont = initFont("linkfont", textFont);

    linkFontMetrics = getFontMetrics(linkFont);

    initMessageSettings();

    initMessages();

    initMessagePositions();

    thread.start();

    }

    public void start() {

    thread.resume();

    }

    public void run() {

    while(true) {

    try {repaint();

    thread.sleep(scrollDelay);

    moveMessages();

    }

    catch(InterruptedException e) {

    }

    }

    }

    public void paint(Graphics g) {

    // Initialize the drawing buffer

    Image drawBuffer = createImage(size.width, size.height);

    Graphics gDraw = drawBuffer.getGraphics();

    // Clear the background

    gDraw.setColor(backColor);

    gDraw.fillRect(0, 0, size.width, size.height);

    if(errorMsg != null) {

    displayError(gDraw);g.drawImage(drawBuffer, 0, 0, null);

    return;

    }

    // Draw the messages

    for(int i = firstMessage; i < numMessages; i++) {

    // Don't draw messages past the right edge

  • 8/7/2019 assignment 4 java

    9/16

    if(Messages[i].x >= size.width)

    break;

    // Don't draw messages past the left edge

    if(Messages[i].x + Messages[i].width < 0) {

    firstMessage = i + 1;

    continue;

    }

    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);

    }

    gDraw.drawString(Messages[i].text, Messages[i].x, y);

    }

    g.drawImage(drawBuffer, 0, 0, null);

    // Cycle after all the messages have scrolled past

    if(firstMessage >= numMessages) {

    firstMessage = 0;

    initMessagePositions();

    }

    }

    public void update(Graphics g) { // Override-don't erase background

    paint(g);

    }

    public void stop() {

    thread.suspend();

    }

  • 8/7/2019 assignment 4 java

    10/16

    public void destroy() {

    thread.stop();

    }

    //

    // Information functions

    //

    public String getAppletInfo() {

    return "Scrolling Marquee. Copyright 1998 Java Resources.";

    }

    public String[][] getParameterInfo() {

    String info[][] = {

    { "bgcolor", "rrggbb", "Background color" },

    { "text", "rrggbb", "Text color" },

    { "link", "rrggbb", "Link color" },

    { "alink", "rrggbb", "Active link color" },

    { "textfont", "face,style,size", "Text font; style = {B|I|BI}" },{ "linkfont", "face,style,size", "Link font; default = textfont" },

    { "scrollamount", "int", "Pixels to move between each sucessive draw" },

    { "scrolldelay", "int", "Milliseconds between each successive draw" },

    { "linkbase", "String", "Absolute base URL for links" },

    { "textN", "String", "Text for message N (\u00A0 specifies gap)" },

    { "linkN", "String", "Link for message N (optional)" }

    };

    return info;

    }

    //

    // Mouse operations

    //

    public boolean mouseEnter(Event evt, int x, int y) {

    mousePos = x;

    return true;}

    public boolean mouseDown(Event evt, int x, int y) {

    AppletContext ac = getAppletContext();

    try {

    if(mouseLink != null) {

  • 8/7/2019 assignment 4 java

    11/16

    URL url = new URL(mouseLink);

    ac.showDocument(url);

    }

    }

    catch(MalformedURLException e) {

    }

    return true;

    }

    public boolean mouseMove(Event evt, int x, int y) {

    mousePos = x;

    return true;

    }

    public boolean mouseDrag(Event evt, int x, int y) {

    mousePos = x;

    return true;

    }

    public boolean mouseExit(Event evt, int x, int y) {mousePos = -1;

    mouseLink = null;

    return true;

    }

    //

    // Parameter initialization functions

    //

    // Get a color value from the applet parameters

    private Color initColor(String param, Color defColor) {

    try {

    String s = getParameter(param);

    if(s != null)

    defColor = new Color(Integer.parseInt(s, 16));

    }

    catch(Exception e) { }

    return defColor;

    }

    // Initialize the font for drawing

    private Font initFont(String param, Font defFont) {

    String s = getParameter(param);

    // If no font is specified, use default

    if(s == null)

  • 8/7/2019 assignment 4 java

    12/16

    return defFont;

    // Get delimiter positions

    int delim1 = s.indexOf(','),

    delim2 = s.indexOf(',', delim1 + 1);

    if(delim1 == -1 || delim2 == -1) {

    errorMsg = "Invalid " + param + ": face,style,size (style=B,I,BI)";

    return defFont;

    }

    // 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(delim2 > delim1 + 1) {

    // Get the font stylefontStyles = s.substring(delim1 + 1, delim2);

    if(fontStyles.indexOf('B') != -1)

    fontStyle |= Font.BOLD;

    if(fontStyles.indexOf('I') != -1)

    fontStyle |= Font.ITALIC;

    }

    if(delim2 < s.length() - 1) {

    try {

    // Get the font size

    fontSize = Integer.parseInt(s.substring(delim2 + 1));

    }

    catch(NumberFormatException e) {

    errorMsg = "Invalid " + param + " size";

    return defFont;

    }

    }

    // Create the font

    return new Font(fontFace, fontStyle, fontSize);}

    private void initMessageSettings() {

    String err = null, s;

    try {

    // Get the scroll amount

  • 8/7/2019 assignment 4 java

    13/16

    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;

    }

    // Get the scroll delay

    if((s = getParameter("scrolldelay")) != null) {

    err = "Invalid scroll delay";

    scrollDelay = Integer.parseInt(s);

    if(scrollDelay < 10)

    scrollDelay = 10;

    }

    if((linkBase = getParameter("linkbase")) == null)

    linkBase = "";}

    catch(NumberFormatException e) {

    errorMsg = err;

    }

    }

    private void initMessages() {

    // Get the messages and initialize their positions

    numMessages = maxMessages;

    Messages = new Message[maxMessages];

    for(int i = 0; i < maxMessages; i++) {

    String paramNum = Integer.toString(i + 1);

    String text = getParameter("text" + paramNum);

    if(text == null) {

    numMessages = i;

    return;

    }

    Messages[i] = new Message();

    if(text.compareTo("\u00A0") == 0) {

    Messages[i].text = "";

    Messages[i].link = null;

    Messages[i].width = size.width;

    } else {

    Messages[i].text = text;

  • 8/7/2019 assignment 4 java

    14/16

    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);

    }

    }

    }

    }

    private void initMessagePositions() {

    int x = size.width;

    for(int i = 0; i < numMessages; i++) {

    Messages[i].x = x;

    x += Messages[i].width;

    }

    }

    //

    // Helper functions

    //

    // Returns the left position for horizontally centered text

    private int getCenteredX(String s, FontMetrics fm) {

    return (size.width - fm.stringWidth(s)) / 2;

    }

    // Returns the baseline position for vertically centered text

    private int getCenteredY(FontMetrics fm) {

    return (size.height + fm.getAscent() - fm.getDescent()) / 2;

    }

    // Displays a centered error message

    private void displayError(Graphics g) {

    g.setColor(textColor);

    g.setFont(textFont);

    g.drawString(errorMsg,getCenteredX(errorMsg, textFontMetrics),

    getCenteredY(textFontMetrics));

    }

    // Move messages

    private void moveMessages() {

    for(int i = 0; i < numMessages; i++)

  • 8/7/2019 assignment 4 java

    15/16

    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;

    }

    public void paint(Graphics g)

    {

    // Shows what was in the HTML param code.

    g.drawString("Parameter 1 is: " + parameter1,20,20);

    g.drawString("Parameter 2 is: " + parameter2,20,40);

    g.drawString("Parameter 3 is: " + parameter3,20,60);

    g.drawString("Parameter 2 + parameter 3 is: " + result,20,80);

    }

    }

    /* This only works when those paramters are actually in the HTML code.

    That code for this example is :

  • 8/7/2019 assignment 4 java

    16/16