Home > database >  How to calculate summation values from multiple JTextFields using loop in java
How to calculate summation values from multiple JTextFields using loop in java

Time:07-25

I am trying to making a calculator. Here the user can add multiple JTextFields to take his/her desired input with just one button click.

Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.

Code:

public class Button extends JFrame {

private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Button frame = new Button();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public Button() {
    initComponents();
}

static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();

int ans, sum = 0;

private void initComponents() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 527, 414);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    
    btnAdd = new JButton("Add");
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            field = new JTextField();
            field.setBounds(45, y  = 60, 284, 32);
            field.setAlignmentX(Component.CENTER_ALIGNMENT);
            contentPane.add(field);
            contentPane.revalidate();
            contentPane.repaint();
        }
    });
    btnAdd.setBounds(170, 341, 89, 23);
    contentPane.add(btnAdd);
    
    btnResult = new JButton("Result");
    btnResult.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < arr.size(); i  ) {
                arr.add(field.getText());
                sum  = Integer.parseInt(arr.get(i));
            }
            resultField.setText(String.valueOf(sum));
        }
    });
    btnResult.setBounds(383, 306, 89, 23);
    contentPane.add(btnResult);
    
    resultField = new JTextField();
    resultField.setBounds(361, 275, 129, 20);
    contentPane.add(resultField);
    resultField.setColumns(10);
}

}

Please help how can I find the correct output?

CodePudding user response:

Suggestions:

  • Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
  • Then in the result button's ActionListener, iterate through this list using a for loop.
  • Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.

Also,

  • Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
  • Having to add your entry fields by button may be an over-complication
  • But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
  • If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.

e.g.,

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class Button2 extends JPanel {
    private List<JSpinner> spinnerList = new ArrayList<>();
    private JButton resultButton = new JButton("Result");
    private JButton addEntryFieldBtn = new JButton("Add Entry Field");
    private JTextField resultField = new JTextField(6);
    private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));

    public Button2() {
        resultField.setFocusable(false);
        resultButton.addActionListener(e -> calcResult());
        resultButton.setMnemonic(KeyEvent.VK_R);
        addEntryFieldBtn.addActionListener(e -> addEntryField());

        JPanel topPanel = new JPanel();
        topPanel.add(addEntryFieldBtn);
        topPanel.add(resultButton);
        topPanel.add(new JLabel("Result:"));
        topPanel.add(resultField);
        
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
        JScrollPane scrollPane = new JScrollPane(centerPanel);
        scrollPane.setPreferredSize(new Dimension(300, 300));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(scrollPane);
    }

    private void calcResult() {
        int sum = 0;
        for (JSpinner spinner : spinnerList) {
            sum  = (int) spinner.getValue();
        }
        resultField.setText(String.valueOf(sum));
    }

    private void addEntryField() {
        JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
        spinner.addChangeListener(evt -> {
            calcResult();
        });
        
        fieldPanel.add(spinner);
        spinnerList.add(spinner);
        revalidate();
        repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Button2 mainPanel = new Button2();

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
  • Related