package com.fr.design.gui.itextfield;

import com.fr.design.event.UIObserver;
import com.fr.design.event.UIObserverListener;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

/**
 * Author : Shockway
 * Date: 13-5-20
 * Time: 上午10:04
 */
public class UIGridTextField extends JTextField implements UIObserver {

	private UIObserverListener uiObserverListener;


	/**
	 *
	 */
	public UIGridTextField() {
		super();
		initListener();
	}

	/**
	 *
	 * @param columns
	 */
	public UIGridTextField(int columns) {
		super(columns);
		initListener();
	}

	/**
	 *
	 * @param text
	 * @param columns
	 */
	public UIGridTextField(String text, int columns) {
		super(text, columns);
		initListener();
	}

	/**
	 *
	 * @param text
	 */
	public UIGridTextField(String text) {
		super(text);
		initListener();
	}

	/**
	 *
	 * @param doc
	 * @param text
	 * @param columns
	 */
	public UIGridTextField(Document doc, String text, int columns) {
		super(doc, text, columns);
		initListener();
	}


	protected void initListener() {
		if (shouldResponseChangeListener()) {
			getDocument().addDocumentListener(new DocumentListener() {
				@Override
				public void insertUpdate(DocumentEvent e) {
					attributeChange();
				}

				@Override
				public void removeUpdate(DocumentEvent e) {
					attributeChange();
				}

				@Override
				public void changedUpdate(DocumentEvent e) {
					attributeChange();
				}
			});
		}
	}

	protected void attributeChange() {
		if (uiObserverListener != null) {
			uiObserverListener.doChange();
		}
	}


	/**
	 *
	 * @param listener 观察者监听事件
	 */
	public void registerChangeListener(UIObserverListener listener) {
		uiObserverListener = listener;
	}

	/**
	 *
	 * @return
	 */
	public boolean shouldResponseChangeListener() {
		return true;
	}
}