Subtraction of two numbers – A swing example

    Let us create subtraction of two numbers using swing. Let us get two numbers from the user as input. The numbers are subtracted, and result is displayed.

Let us implement this program in swing.

Program implementation:

  • First, include the packages javax.swing,java.awt and its sub packages.
  • Create a public class with main function.
  • Create the objects for swing components as follows.
  • o   A new frame object is created for subtraction purpose.
  • o   Two text fields are created for input.
  • o   A label caption is set to ‘-‘.
  • o   A button is designed for subtraction.
  • o   Sub label is designed for result.
  • A panel structure is designed.
  • Now, Add the components to the panel. Two text fields, a button, label and sub label.
  • Let us add the code for button event.
  • Get the numbers from the user. Integer.parseInt(number) gives the translation of text into number.
  • Subtract it and display it into the result label.
  • Finally, add the panel to frame and pack it.
  • Set the default close operation as EXIT_ON_CLOSE
  • Make the frame visible by setVisible as true.

Program:

//include the built-in packages

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

// class definition starts here

public class swingCalculator {

//main() function

    public static void main(String[] args) {

//swing components creation

        JFrame frame = new JFrame("Subtraction");

        JTextField txtField1 = new JTextField(5);

        JTextField txtField2 = new JTextField(5);

        JLabel pLabel = new JLabel("-");

        JButton button1 = new JButton("sub");

        JLabel subLabel = new JLabel("Result: ");

         JPanel panel1 = new JPanel();

        panel1.add(txtField1);

        panel1.add(pLabel);

        panel1.add(txtField2);

        panel1.add(button1);

        panel1.add(subLabel);

         button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                try {

                    int no1 = Integer.parseInt(txtField1.getText());

                    int no2 = Integer.parseInt(txtField2.getText());

                    int result = no1 - no2;

                    subLabel.setText("Result: " + result);

                } catch (NumberFormatException ex) {

                    JOptionPane.showMessageDialog(frame, "Please enter valid numbers!");

                }

            }

        });

        frame.add(panel1);

        frame.pack();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true);

    }

}

Output:

Hope this program implementation is useful to you. Keep Coding!!!

No comments:

Post a Comment