Skip to content

Instantly share code, notes, and snippets.

@navin-mohan
Created June 4, 2017 16:45
Show Gist options
  • Select an option

  • Save navin-mohan/ffc2d9aa32556791f81eece0bb32a7f8 to your computer and use it in GitHub Desktop.

Select an option

Save navin-mohan/ffc2d9aa32556791f81eece0bb32a7f8 to your computer and use it in GitHub Desktop.
Calculator Applet using AWT Java
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class SimpleCalc extends Applet{
private Label xInputLabel,yInputLabel;
private Label statusLabel;
private Panel xInputPanel;
private Panel yInputPanel,operations;
private Label msgLabel;
private TextField xInputText,yInputText;
private Button add,sub,mul,div;
public void init(){
prepareGUI();
}
private void prepareGUI(){
CalculateActionListener ce = new CalculateActionListener();
xInputLabel = new Label("X = ");
xInputLabel.setAlignment(Label.RIGHT);
yInputLabel = new Label("Y = ");
yInputLabel.setAlignment(Label.RIGHT);
msgLabel = new Label("X + Y = 0");
msgLabel.setAlignment(Label.CENTER);
xInputText = new TextField("0");
yInputText = new TextField("0");
add = new Button("+");
sub = new Button("-");
mul = new Button("*");
div = new Button("/");
add.addActionListener(ce);
sub.addActionListener(ce);
mul.addActionListener(ce);
div.addActionListener(ce);
xInputPanel = new Panel();
xInputPanel.setLayout(new GridLayout(1,2));
yInputPanel = new Panel();
yInputPanel.setLayout(new GridLayout(1,2));
operations = new Panel();
operations.setLayout(new GridLayout(1,4));
xInputPanel.add(xInputLabel);
xInputPanel.add(xInputText);
yInputPanel.add(yInputLabel);
yInputPanel.add(yInputText);
operations.add(add);
operations.add(sub);
operations.add(mul);
operations.add(div);
setLayout(new GridLayout(4,1));
add(xInputPanel);
add(yInputPanel);
add(operations);
add(msgLabel);
}
private class CalculateActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
double x = Double.parseDouble(xInputText.getText());
double y = Double.parseDouble(yInputText.getText());
byte flag = 0;
switch(e.getActionCommand()){
case "+":
x +=y;
break;
case "-":
x-=y;
break;
case "*":
x*=y;
break;
case "/":
if(y==0) flag = 1;
else
x /= y;
break;
default: flag = 1;
}
if (flag == 0){
msgLabel.setText("X " + e.getActionCommand() + " Y =" + x);
}else{
msgLabel.setText("Error..Check the input values");
}
}
}
}
/*
<applet code = "SimpleCalc" width = 400 height = 400> </applet>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment