Write a program using swing components to add two numbers. Use text fields for inputs and output. Your program should display the result when the user presses a button.

 Swing simple calculator


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class Calculator extends JFrame implements ActionListener{

JLabel l1,l2,l3;

JTextField t1,t2,t3;

JButton btn1,btn2;

public Calculator(){

l1 = new JLabel("Enter 1st number");

t1 = new JTextField(20);

l2 = new JLabel("Enter 2nd number");

l3 = new JLabel("Result");

t3 = new JTextField(20);

btn1= new JButton("+");
btn2 = new JButton("-");
t2 = new JTextField(20);

add(l1);

add(t1);

add(l2);

add(t2);

add(l3);

add(t3);

add(btn1);

add(btn2);

setSize(390,390);

setLayout(new FlowLayout(FlowLayout.LEFT));

setVisible(true);

btn1.addActionListener(this);

btn2.addActionListener(this);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed (ActionEvent ae){

String s1,s2;

s1 =t1.getText();

s2 = t2.getText();

int n1,n2,n3;

n1 = Integer.parseInt(s1);

n2 = Integer.parseInt(s2);

if(ae.getSource()==btn1)

n3 = n1+n2;

else

n3 = n1-n2;

t3.setText(String.valueOf(n3));

}

public static void main(String[] args) {
new Calculator();
}

}

Reactions

Post a Comment

0 Comments