Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTextField focus listener called twice...

843806Nov 1 2007
Hi,

I am just trying to create a text field component, which gives an error when user enter invalid data and tries to move out of the control. It should display an error message and get the focus back to the text field.

My problem is this error message is being poped-up more than once...
My code snippet...
package com.common.ui.controls;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class ValidationTextField extends JTextField 
{
	private String errorString = "Please enter a valid data.";
	private TextFieldValidator validator;
	
	public ValidationTextField(int cols,TextFieldValidator validator)
	{
		this(null,cols,validator);
	}
	
	public ValidationTextField(String text,int cols,TextFieldValidator validator)
	{
		super(text,cols);
		setValidator(validator);
		addFocusListener(new TextFieldFocusListener());
	}
	
	class TextFieldFocusListener implements FocusListener
	{
		public void focusGained(FocusEvent e) 
		{
			
		}

		public void focusLost(FocusEvent e) 
		{
			final ValidationTextField field = (ValidationTextField) e.getComponent();
			//Thread.dumpStack();
			if(!e.isTemporary() && field.isEditable() && field.isEnabled() && field.isVisible())
			{
				if(!validator.isValid(field))
				{
					field.removeFocusListener(this);
					JOptionPane.showMessageDialog(field.getParent(), getErrorString(), "Error", JOptionPane.ERROR_MESSAGE);
					field.requestFocusInWindow();
					field.addFocusListener(this);		

				}
			}
		}
		
	}
	
	public String getErrorString() {
		return errorString;
	}

	public void setErrorString(String errorString) {
		this.errorString = errorString;
	}

	public TextFieldValidator getValidator() {
		return validator;
	}

	public void setValidator(TextFieldValidator validator) {
		this.validator = validator;
	}
}
I feel that the problem is because of displaying a pop-up dialog. so I tried to remove the focus listener before showing the pop-up and add it back after it. But even that does n't work...

any suggestion on this is appreciated...

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 29 2007
Added on Nov 1 2007
0 comments
188 views