0% found this document useful (0 votes)
2 views

java Practical 22

The document contains Java code for a simple GUI application called AdditionApp that allows users to input two numbers and displays their sum. It uses Swing components such as JTextField, JButton, and JLabel, and handles user input with an ActionListener. The application also includes error handling to prompt the user for valid number entries if the input is incorrect.

Uploaded by

londheprerana72
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java Practical 22

The document contains Java code for a simple GUI application called AdditionApp that allows users to input two numbers and displays their sum. It uses Swing components such as JTextField, JButton, and JLabel, and handles user input with an ActionListener. The application also includes error handling to prompt the user for valid number entries if the input is incorrect.

Uploaded by

londheprerana72
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Practical 22: Q4

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AdditionApp extends JFrame
{
private JTextField num1Field, num2Field, resultField;
private JButton addButton;
public AdditionApp()
{
setTitle("Addition App");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 5, 5));
JLabel num1Label = new JLabel("Enter Number 1:");
num1Field = new JTextField();
JLabel num2Label = new JLabel("Enter Number 2:");
num2Field = new JTextField();
addButton = new JButton("Add");
resultField = new JTextField();
resultField.setEditable(false);
addButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
performAddition();
}
});
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(addButton);
add(new JLabel("Result:"));
add(resultField);
setVisible(true);
}
private void performAddition()
{
try
{
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double sum = num1 + num2;
resultField.setText(String.valueOf(sum));
} catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(this, "Please enter valid numbers!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args)
{
new AdditionApp();}}

You might also like