0

I have created a console Application and now I'm starting to convert it into a swing Application. I have one question and I searched many times for an answer but I didn't find any.

My application has an class which validates the input of the user and also if the input is wrong it gives a error msg into console. So what I try to do is, I have an Jtextfield and validate this input, if the input is wrong it should give me the error msg.

That's my Input class where the User is allowed to write

public class Input {

    private static BufferedReader eingabe = new BufferedReader(new InputStreamReader(System.in));
    private Output output = new Output();
    
    private static String captureText() throws Exception {
        return eingabe.readLine();
    }
    public String formatInput() {
        boolean again = true;

        while (again) {
            try {
                String format = captureText();

                if (!format.equalsIgnoreCase("Y") && !format.equalsIgnoreCase("N")) {
                    again = true;
                    throw new Exception();
                }
                again = false;
                return format;
            } catch (Exception e) {
                this.output.formatInputWrong();
            }
        }
        return null;

    }
}

That's my output class method

void formatInputWrong() {
    System.out.print("\nThe Format Input is wrong.");
           
}

I just want to know can I use the Validation of the Input class or should I create a special class for the swing input validation because I know I can take out the Input of the JTextfield?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 3
    It really depends on what type of fields you're trying to validate - you could use an `InputVerifier`, it's post validation process, or for text components a `DocumentListener` or `DocumentFilter` – MadProgrammer Jul 01 '17 at 08:01
  • 1
    You could also do post validation through an `ActionListener` attached to a `JButton` – MadProgrammer Jul 01 '17 at 08:23
  • Yeah I would make it with the button but the normal console Validation dont work am I right? So that code what I am posted is a example how my console validation worked. – ManuellsenDeve Jul 01 '17 at 08:26
  • 1
    Most GUIs are event driven frameworks, that is, something happens and you respond to it. It can take a little getting use to. Basically, you won't need a loop of any kind (that's taken care for you) and you simply respond to the appropriate events when they a triggered – MadProgrammer Jul 01 '17 at 09:17

1 Answers1

3

Your error message now appears on the console. It looks like you want the message to appear in the GUI. As shown in How to Use the Focus Subsystem: Validating Input, InputVerifier is a good choice. Because your implementation of shouldYieldFocus() is permitted to have sided effects, you can update a status display as needed. Starting from this complete example, the variation below adds a JLabel and conditions it in shouldYieldFocus() according to the result of calling verify().

private static final String OK = "Values OK.";
private JLabel status = new JLabel(OK, JLabel.CENTER);
…
if (verify(input)) {
    …
    status.setText(OK);
    return true;
} else {
    …
    status.setText("Please enter a number.");
    return false;
}

A complementary approach might include a DocumentListener, as suggested here.

image

import java.awt.*;
import javax.swing.*;

/**
 * @see http://stackoverflow.com/a/44861290/230513
 * @see http://stackoverflow.com/a/11818183/522444
 */
public class VerifierEg {

    private static final String ZERO = "0.0";
    private static final String OK = "Values OK.";
    private JTextField field1 = new JTextField(ZERO, 5);
    private JTextField field2 = new JTextField(ZERO, 5);
    private JTextField resultField = new JTextField(ZERO, 10);
    private JLabel status = new JLabel(OK, JLabel.CENTER);

    private void createAndShowGui() {
        resultField.setEditable(false);
        resultField.setFocusable(false);

        JPanel mainPanel = new JPanel();
        final JTextField[] fields = {field1, field2};

        mainPanel.add(field1);
        mainPanel.add(new JLabel(" x "));
        mainPanel.add(field2);
        mainPanel.add(new JLabel(" = "));
        mainPanel.add(resultField);

        for (JTextField field : fields) {
            field.setInputVerifier(new MyInputVerifier(field));
        }

        JFrame frame = new JFrame("VerifierEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.add(status, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void calcProduct() {
        double d1 = Double.parseDouble(field1.getText());
        double d2 = Double.parseDouble(field2.getText());
        double prod = d1 * d2;
        resultField.setText(String.valueOf(prod));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                VerifierEg eg = new VerifierEg();
                eg.createAndShowGui();
            }
        });
    }

    /**
    * @see http://stackoverflow.com/a/11818946/230513
    */
    private class MyInputVerifier extends InputVerifier {

        private JTextField field;
        private double value;

        public MyInputVerifier(JTextField field) {
            this.field = field;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
            if (verify(input)) {
                field.setText(String.valueOf(value));
                calcProduct();
                status.setText(OK);
                return true;
            } else {
                field.setText(ZERO);
                field.selectAll();
                status.setText("Please enter a number.");
                return false;
            }

        }

        @Override
        public boolean verify(JComponent input) {
            try {
                value = Double.parseDouble(field.getText());
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045