Blogroll

This blog is created for education about engineering students.All the engineering students are get free downloadable books here. not only books and also different software also available here

7. simple calculator


Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
//
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends Applet implements ActionListener
{
JTextField t1,t2,t3;
JLabel l1,l2,l3;
JButton b1,b2,b3,b4;
JPanel p1,p2;
public void init()
{
p1=new JPanel();
p2=new JPanel();
p1.setBackground(Color.gray);
p2.setBackground(Color.gray);
setBackground(Color.lightGray);
l1=new JLabel("Enter the First number :");
p1.add(l1);
t1=new JTextField(10);
p1.add(t1);
l2=new JLabel("Enter the Second number :");
p1.add(l2);
t2=new JTextField(10);
p1.add(t2);
l3=new JLabel("Result");
p1.add(l3);
t3=new JTextField(10);
p1.add(t3);
b1=new JButton("ADD");
p2.add(b1);
b1.addActionListener(this);
b2=new JButton("SUB");
p2.add(b2);
b2.addActionListener(this);
b3=new JButton("MUL");
p2.add(b3);
b3.addActionListener(this);
b4=new JButton("DIVISION");
p2.add(b4);
b4.addActionListener(this);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
t1.setBackground(Color.yellow);
t2.setBackground(Color.yellow);
t3.setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae)
{
try
{
if (ae.getSource()==b1)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sum=x+y;
t3.setText(" "+sum);
}
if (ae.getSource()==b2)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sub=x-y;
t3.setText(" "+sub);
}
if (ae.getSource()==b3)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int mul=x*y;
t3.setText(" "+mul);
}
if (ae.getSource()==b4)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int div=x/y;
t3.setText(" "+div);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
}

No comments:

Post a Comment

Total Pageviews