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
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.
Example:
Go through the following example: Your all concepts related to Swing will get cleared. Output is given at the end of this post.
SwingAddition.java
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"); add(l1); add(t1); add(l2); add(t2); add(b); add(l3); b.addActionListener(this); setVisible(true); setSize(250,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { int num1=Integer.parseInt(t1.getText()); int num2=Integer.parseInt(t2.getText()); int value=num1+num2; l3.setText(""+value); } } |
How To Run:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac SwingAddition.java
parag@parag-Inspiron-N4010:~/Desktop/prog$ java SwingAddition |
Output:
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