Thursday, 20 January 2022

Add Two Numbers in JAVA using GUI (awt, swing, event handling)


 import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class MyFrameSample  extends JFrame implements ActionListener

{


JButton btn;

JTextField[] txt;

MyFrameSample()

{

txt=new JTextField[3];//initializing array of text fields

btn=new JButton("Click Me");//initializing button

txt[0]=new JTextField("Enter a");//it will be used to take number as input

txt[1]=new JTextField("Enter b");

txt[2]=new JTextField("a+b = ");//result will be set here

btn.addActionListener(this);//it register action listener with button and this(out frame) will

// handle action event

add(txt[0]);

add(txt[1]);

add(txt[2]);

add(btn);

}

public void actionPerformed(ActionEvent e)//on button click this will be called

{

int a=Integer.parseInt(txt[0].getText());//converting string into integer

int b=Integer.parseInt(txt[1].getText());

int c=a+b;

txt[2].setText(""+c);

}

}

class FrameDemoSample

{

public static void main(String args[])

{

MyFrameSample x=new MyFrameSample();

x.setLayout(new FlowLayout());//setting layout

x.setSize(300,400);//setting size

x.setTitle("My Frame Sample");//title

x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//cross button working

x.setVisible(true);//frame will be visible now

}

}

#JAVA #awt #swing #events #frames #jframe #java 

No comments:

Post a Comment