Tuesday, 22 August 2017

Java Swing Program To Add Two Numbers | Java Swing program For Addition of Two Numbers

                    In this post, we will see Java Swing Program To Add Two Numbers | Java Swing program For Addition of Two Numbers 
                    To know What is Swing, How Swing is different from Applet, How to create Swing Application; check this post http://www.comrevo.com/2017/08/swing-in-java-with-example.html               

Watch following video: 

Watch on YouTube: https://www.youtube.com/watch?v=c6xPxY45WVg          

How to generate event in Swing?
                    To generate event in Swing, we have to register component (say button) for event by calling method addActionListener(). This method accepts object of ActionListener interface. As we can not create object of interface, we have to implement ActionListener interface into class and we can pass object of this class to addActionListener() method as argument. this represents the current object of class.
                    addActionListener() implicitly call method actionPerformed(). This method accepts object of ActionEvent class as argument. actionPerformed() method is declared in ActionListener interface. 
                    Whatever the action we have to take for event, we have to mention in actionPerformed() method.
                 Go through the following example: Your all concepts related to Swing will get cleared. Output is given at the end of this post.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingAddition
   public static void main(String args[])
       Abc obj=new Abc();

class Abc extends JFrame implements ActionListener
  JLabel l1;
  JTextField t1;
  JLabel l2;
  JTextField t2;
  JButton b;
  JLabel l3;

  public Abc()
     setLayout(new FlowLayout());

     l1=new JLabel("First Number:");
     t1=new JTextField(20); 
     l2=new JLabel("Second Number:");
     t2=new JTextField(20);
     b=new JButton("Add");

     l3=new JLabel("Result");



 public void actionPerformed(ActionEvent ae)
    int num1=Integer.parseInt(t1.getText());
    int num2=Integer.parseInt(t2.getText());
    int value=num1+num2;


How To Run:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac SwingAddition.java 
parag@parag-Inspiron-N4010:~/Desktop/prog$ java SwingAddition

                        Check for Java Swing Program for Calculator in this post http://www.comrevo.com/2017/08/java-swing-calculator-program.html

                        Check other posts on Java Programming in this link http://www.comrevo.com/2017/08/java-programming.html

No comments:

Post a comment