package javaapplication4;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import java.lang.*;
public class JavaApplication4 extends JFrame
{
JLabel l1,l2;
JButton b1,b2,b3,b4;
JTextField t1,t2,r;
public JavaApplication4()
{
setLayout( new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
l1= new JLabel("Num1");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
add(l1,c);
t1 = new JTextField(10);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=0;
c.gridwidth=3;
add(t1,c);
l2= new JLabel("Num2");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=1;
add(l2,c);
t2 = new JTextField(10);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=1;
c.gridwidth=3;
add(t2,c);
b1 = new JButton("+");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=2;
c.gridwidth=1;
add(b1,c);
b2 = new JButton("-");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=2;
c.gridwidth=1;
add(b2,c);
b3 = new JButton("*");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=2;
c.gridy=2;
add(b3,c);
c.gridwidth=1;
b4 = new JButton("/");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=3;
c.gridy=2;
c.gridwidth=1;
add(b4,c);
r = new JTextField("Result");
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=3;
c.gridwidth=4;
add(r,c);
event e = new event();
b1.addActionListener(e);
b2.addActionListener(e);
b3.addActionListener(e);
b4.addActionListener(e);
}
public class event implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double number1,number2;
try
{
number1 =(int)(Double.parseDouble(t1.getText()));
}
catch(NumberFormatException a)
{
r.setText("Invalid Value In Field 1");
return;
}
try
{
number2 =(int)(Double.parseDouble(t2.getText()));
}
catch(NumberFormatException a)
{
r.setText("Invalid Value In Field 2");
return;
}
String s = e.getActionCommand();
if(s.equals("+"))
{
double sum;
sum= number1+number2;
r.setText(number1 + "+"+number2 + "=" + sum);
}
if(s.equals("-"))
{
double sum;
sum= number1-number2;
r.setText(number1 + "-"+number2 + "=" + sum);
}
if(s.equals("*"))
{
double sum;
sum= number1*number2;
r.setText(number1 + "*"+number2 + "=" + sum);
}
if(s.equals("/"))
{
double sum;
if(number2==0)
{
r.setText("Cannot Divide By Zero");
}
else{sum= number1/number2;
r.setText(number1 + "/"+number2 + "=" + sum);
}
}
}
}
public static void main(String[] args) {
JavaApplication4 gui = new JavaApplication4();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Simple Calculator");
gui.setVisible(true);
gui.setSize(500, 500);
}
}
ConversionConversion EmoticonEmoticon