views:

39

answers:

2

Hello,

I am working on a form that provides "real-time" validation to the user and I have one problem.

The goal is to put a label near the field (in this case a JSpinner), to show the user if the data is accepted or denied, in the same way that javascript-based validators do.

The problem is that for archieving this, I need to set the value for the corresponding label and the only way I have found to do this is to create as many verifiers as fields, this way:

class MyVerifier extends InputVerifier{

    static final double MAX_VALUE = 30;

    @Override
    public boolean verify(JComponent input) {
        JTextField tf = (JTextField) input;
        Double value = Double.parseDouble(tf.getText().replace(',', '.'));
        return (value>1);
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        boolean isValid = super.shouldYieldFocus(input);
    if (isValid) {
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("resources/accept.png")));
            jLabel1.setText("");
    } else {
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("resources/exclamation.png")));
            jLabel1.setText("The number of items must be greater than 1");
    }
        return true;
    }
 }

Then, the same code for jLabel2... It must be another way to do this.

Thanks in advance.

+1  A: 

You could have a Hashmap for the text field and its related label component. Then in the shouldYieldFocus method you retrieve the related label for the text field being validated. You can then set the text/icon of the label appropriately.

You would probably also need a secound Hashmap containg the label and the text message for the error.

camickr
Perfect, thanks!
rlbisbe
A: 

You could also use a JDialog as a popup next to the JComponent you are validating. This popup JDialog will have a JLabel that will encapsulate the message you want to display next to the respective Jcomponent. All you have to do is to calculate the position of the popup relative to the Jcomponent you are validating.

You can find a good example here

walters