Write a program that performs the basic two mathematical operations addition and subtraction using Layout manager.( File must be save as :Assignment12.java)
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
class Addition extends JFrame
{
JButton button1=new JButton("Addition");
JButton button2=new JButton("Subtraction");
JLabel label1=new JLabel("1st Number: ");
JLabel label2=new JLabel("2nd Number: ");
JLabel label3=new JLabel("Result :");
JTextField textField1=new JTextField("",10);
JTextField textField2=new JTextField("",10);
JTextField textField3=new JTextField("",10);
GridBagConstraints c=new GridBagConstraints();
GridBagLayout layout=new GridBagLayout();
public Addition()
{
super("Addition of 2 number's");
setLayout(layout);
c.gridx=0;
c.gridy=0;
layout.setConstraints(label1,c);
add(label1);
c.gridx=1;
c.gridy=0;
layout.setConstraints(textField1,c);
add(textField1);
c.gridx=0;
c.gridy=1;
layout.setConstraints(label2,c);
add(label2);
c.gridx=1;
c.gridy=1;
layout.setConstraints(textField2,c);
add(textField2);
c.gridx=0;
c.gridy=2;
layout.setConstraints(label3,c);
add(label3);
c.gridx=1;
c.gridy=2;
layout.setConstraints(textField3,c);
add(textField3);
c.gridx=0;
c.gridy=3;
c.insets=new Insets(10,75,0,0);
layout.setConstraints(button1,c);
add(button1);
c.gridx=1;
c.gridy=3;
c.insets=new Insets(10,0,0,0);
layout.setConstraints(button2,c);
add(button2);
Calculation cal=new Calculation();
button1.addActionListener(cal);
button2.addActionListener(cal);
}
class Calculation implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
int a=Integer.valueOf(textField1.getText());
int b=Integer.valueOf(textField2.getText());
if(event.getSource()==button1)
textField3.setText(String.valueOf(a+b));
else if(event.getActionCommand()=="Subtraction")
textField3.setText(String.valueOf(a-b));
}
}
}
public class Assignment12
{
public static void main(String args[])
{
Addition addition=new Addition();
addition.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addition.setSize(400,300);
addition.setVisible(true);
}
}////////////////////////////////////////////
Copy & paste this code in your Textpad & run, then you will get output.......
If you have any problem please comment below.........