Home > Enterprise >  looping a validation consecutively
looping a validation consecutively

Time:03-02

I am currently trying to figure out a way how to loop a validation to where when a button is pressed, it will validate the JTextfield inputs then print something in a dialog in which after "OK" is pressed, it will keep cycling this validation till it hits the value of times. I assume I would use a for loop but I am genuinely confused on where it would be inputted. After it has reached the value of the times, I would just frame.setVisible(false) and hide it.

btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         String txtField = testTextField.getText();
          int times = 3;
          if (firstNameInvalid(txtField) == false) {
             JOptionPane.showMessageDialog(null, "input valid text field");
          } else {
              JOptionPane.showMessageDialog(null, "gratz, onto the next !!");
          }
     }
});

CodePudding user response:

I assume I would use a for loop

No, you shouldn't. While this solution works for linear console programs, this is not a viable solution for event driven GUI code.

Instead, create state fields, variables, that you change as input is given, and base the program's response to values held by these state fields.

the main goal is for the user to enter a name, that name then is stored into an arraylist, then the frame will refresh itself and allow for another name to be inputted and stored, this cycle will continue till it reaches the 'times' variable.

Then you could conceivably make an List<String> nameList = new ArrayList<>(); your key variable, and the .size() of this list the state that your program follows.

Each time the ActionListener is activated, it gets the text from the JTextField and adds it to the nameList. Then it checks the nameList.size() if equal to your times variable, you're done, and then need to do whatever processing is required on completion of the task.

But again, a for-loop is not helpful here since you're not actually looping. If you used a for loop, like you would when getting Scanner input, you'd freeze the GUI by blocking its event thread. Everything in an event-driven program should be driven by, well, events: listen to events and respond to events.

CodePudding user response:

Keep track of the number of times you've validated the input, compare to the number of times you need to loop, make decisions as required

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new InputPane(3, new InputPane.Observer() {
                    @Override
                    public void didCompleteInput(InputPane source, List<String> names) {
                        frame.dispose();
                    }
                }));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class InputPane extends JPanel {

        public interface Observer {
            public void didCompleteInput(InputPane source, List<String> names);
        }

        private JTextField nameField;
        private JButton nextButton;
        private JProgressBar progressBar;
        private JLabel currentCountLabel;

        private int index = 1;

        private List<String> names;
        private Observer observer;

        public InputPane(int count, Observer observer) {
            this.observer = observer;
            setBorder(new EmptyBorder(32, 32, 32, 32));
            nameField = new JTextField(20);
            nextButton = new JButton("Next");
            progressBar = new JProgressBar(0, count);
            progressBar.setValue(1);
            currentCountLabel = new JLabel("1");

            names = new ArrayList<>(count);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            gbc.fill = gbc.HORIZONTAL;

            JPanel inputPane = new JPanel();
            inputPane.add(new JLabel("Name: "));
            inputPane.add(nameField);

            add(inputPane, gbc);

            JPanel progressPane = new JPanel(new GridBagLayout());
            gbc = new GridBagConstraints();
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1;
            gbc.gridx = 0;
            gbc.gridy = 0;
            progressPane.add(progressBar, gbc);
            gbc.gridx  ;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            gbc.insets = new Insets(0, 8, 0, 0);
            progressPane.add(currentCountLabel, gbc);
            gbc.gridx  ;
            gbc.insets = new Insets(0, 0, 0, 0);
            progressPane.add(new JLabel("/"   Integer.toString(count)));

            gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            gbc.fill = gbc.HORIZONTAL;
            add(progressPane, gbc);

            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.LINE_END;
            add(nextButton, gbc);

            nextButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String name = nameField.getText();
                    nameField.setText(null);
                    if (name.isBlank()) {
                        JOptionPane.showMessageDialog(InputPane.this, "Nope");
                    } else {
                        names.add(name);
                        index  ;
                        progressBar.setValue(Math.min(index, count));
                        currentCountLabel.setText(Integer.toString(Math.min(index, count)));
                        if (index > count) {
                            observer.didCompleteInput(InputPane.this, names);
                        }
                    }
                }
            });
        }
    }
}
  • Related