Add multiple number input fields with JOptionPane and display the sum in Console with Java

Java 8Object Oriented ProgrammingProgramming

At first, set multiple number input fields −

JTextField text1 = new JTextField(10);
JTextField text2 = new JTextField(10);
JTextField text3 = new JTextField(10);
JTextField text4 = new JTextField(10);
JTextField text5 = new JTextField(10);
JTextField text6 = new JTextField(10);
JTextField text7 = new JTextField(10);
JTextField text8 = new JTextField(10);
panel.add(text1);
panel.add(text2);
panel.add(text3);
panel.add(text4);
panel.add(text5);
panel.add(text6);
panel.add(text7);
panel.add(text8);

Now, let us add the values of the multiple number input fields created above −

System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +
   Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+
   Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+
   Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));

Above, we have displayed the sum in the Console.

The following is an example to sum multiple number input fields with JOptionPane −

Example

package my;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new GridLayout(5, 3));
      JTextField text1 = new JTextField(10);
      JTextField text2 = new JTextField(10);
      JTextField text3 = new JTextField(10);
      JTextField text4 = new JTextField(10);
      JTextField text5 = new JTextField(10);
      JTextField text6 = new JTextField(10);
      JTextField text7 = new JTextField(10);
      JTextField text8 = new JTextField(10);
      panel.add(text1);
      panel.add(text2);
      panel.add(text3);
      panel.add(text4);
      panel.add(text5);
      panel.add(text6);
      panel.add(text7);
      panel.add(text8);
      JOptionPane.showMessageDialog(null, panel);
      System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +
         Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+
         Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+
         Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));
   }
}

Output

Now, enter the numbers in the TextField and click OK −

On pressing OK above, the result would be visible in the Console that is sum of all the numbers added above −

raja
Updated on 30-Jul-2019 22:30:26

Advertisements