CJ_Slip_4B

Slip No.4

B) Write a java program using Applet to implement a simple arithmetic calculator.

1. Open Notepad.

2. Type the following code:

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

    public class SimpleCalculator extends Applet implements ActionListener {
    TextField num1, num2, result;
    Button add, subtract, multiply, divide;

    public void init() {
    // Set layout for the applet
    setLayout(new GridLayout(5, 2));

    // Initialize the components
    num1 = new TextField();
    num2 = new TextField();
    result = new TextField();
    result.setEditable(false);

    add = new Button("+");
    subtract = new Button("-");
    multiply = new Button("*");
    divide = new Button("/");

    // Add components to the applet
    add(new Label("Number 1:"));
    add(num1);
    add(new Label("Number 2:"));
    add(num2);
    add(new Label("Result:"));
    add(result);
    add(add);
    add(subtract);
    add(multiply);
    add(divide);

    // Add action listeners
    add.addActionListener(this);
    subtract.addActionListener(this);
    multiply.addActionListener(this);
    divide.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
    double n1 = Double.parseDouble(num1.getText());
    double n2 = Double.parseDouble(num2.getText());
    double res = 0;

    if (e.getSource() == add) {
    res = n1 + n2;
    } else if (e.getSource() == subtract) {
    res = n1 - n2;
    } else if (e.getSource() == multiply) {
    res = n1 * n2;
    } else if (e.getSource() == divide) {
    res = n1 / n2;
    }

    result.setText(String.valueOf(res));
    }
    }



3. Save the file with the name SimpleCalculator.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Create an HTML file to run the applet. Save the following code in a file named SimpleCalculator.html:
    <html>
    <body>
    <applet code="SimpleCalculator.class" width="400" height="200">
    </applet>
    </body>
    </html>

5. Open the Command Prompt.

6. Compile the Java program by typing:
javac SimpleCalculator.java

7. Run the applet using an applet viewer or a compatible web browser. You can use the appletviewer tool that comes with the JDK to run the HTML file:
appletviewer SimpleCalculator.html

No comments:

Post a Comment