Java Programming
Java Programming
St Id: 1710477133
Problem 1: Write a GUI program to perform the following operations (Use separate button for each operations and
text fields for inputs and output): (a) addition (b) subtraction (b) multiplication (c) division
Answer:
import java.awt.*;
import java.awt.event.*;
JavaGUIApp1() {
resultField.setEditable(false);
addWindowListener(new WindowAdapter() {
@Override
dispose();
});
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
add(textfieldlabel_1);
add(textfield1);
add(textfieldlabel_2);
add(textfield2);
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(resultField);
setLayout(new FlowLayout());
setSize(300, 400);
setResizable(false);
setVisible(true);
}
@Override
try {
num1 = Double.parseDouble(textfield1.getText());
num2 = Double.parseDouble(textfield2.getText());
if(source == addButton)
result = Double.toString(num1+num2);
result = Double.toString(num1-num2);
result = Double.toString(num1*num2);
result = Double.toString(num1/num2);
} catch (Exception e) {
result = "Error!";
resultField.setText(result);
Problem 2: Write a GUI program to perform the Clear and Undo functions of a Text Field (Use separate
button for each operations and Text Fields for inputting text message).
Answer:
import java.awt.*;
import java.awt.event.*;
public class JavaGUIApp2 extends Frame implements ActionListener {
JavaGUIApp2() {
addWindowListener(new WindowAdapter() {
@Override
dispose();
});
CLearButton.addActionListener(this);
UndoButton.addActionListener(this);
add(TextFieldLabel);
add(textfield);
add(CLearButton);
add(UndoButton);
setLayout(new FlowLayout());
setSize(300, 400);
setResizable(false);
setVisible(true);
}
new JavaGUIApp2();
@Override
String text;
try {
text = textfield.getText();
temp = text;
textfield.setText("");
if(!temp.isBlank())
textfield.setText(temp);
} catch (Exception e) {
System.out.println(e);