Basic Addition Program in Java AWT


In this program, You will learn how to add two numbers using awt in Java.

  • The program defines a class MyApp which extends the Frame class and implements the ActionListener interface. The MyApp class contains a constructor which initializes the GUI components such as labels, text fields, and a button.
  • The actionPerformed() method of the ActionListener interface is implemented, which is called when the button is clicked. Inside the method, the values entered in the text fields are extracted, converted to integers, added, and the result is displayed in a label.
  • If the text fields are empty, then the l3 label displays a message requesting the user to input the data.
  • The main() method creates an object of MyApp and displays it on the screen.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//Basic Addition Program in Java AWT
class MyApp extends Frame implements ActionListener {
 
	Label l1, l2, l3;
	TextField txt1;
	TextField txt2;
	Button b;
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
 
		l1 = new Label("Enter The Value 1 : ");
		l1.setBounds(10, 50, 100, 30);
 
		txt1 = new TextField();
		txt1.setBounds(150, 50, 250, 30);
 
		l2 = new Label("Enter The Value 2 : ");
		l2.setBounds(10, 100, 100, 30);
 
		txt2 = new TextField();
		txt2.setBounds(150, 100, 250, 30);
 
		b = new Button("Click Me");
		b.setBounds(150, 150, 100, 30);
		b.addActionListener(this);
 
		l3 = new Label("--");
		l3.setBounds(10, 200, 300, 30);
 
		add(l1);
		add(txt1);
		add(l2);
		add(txt2);
		add(b);
		add(l3);
 
		// Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
	@Override
	public void actionPerformed(ActionEvent e) {
		String s1 = txt1.getText();
		String s2 = txt2.getText();
		if(s1.isEmpty() || s2.isEmpty()) {
       	 l3.setText("Please Enter The data");    
       }else {
	        int a = Integer.parseInt(s1);    
	        int b = Integer.parseInt(s2);    
	        int c = a+b;
	        String result = String.valueOf(c);    
	        l3.setText("Total :"+result);    
	        }
 
	}
 
}
 
public class app {
	public static void main(String[] args) {
		MyApp frm = new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs