/**
 *  Licensed under GPL. For more information, see
 *    http://jaxodraw.sourceforge.net/license.html
 *  or the LICENSE file in the jaxodraw distribution.
 */
package net.sf.jaxodraw.gui.swing.spinner;

import java.awt.Component;
import java.awt.Font;

import javax.swing.JComponent;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.plaf.UIResource;


/** Fixed JSpinner that avoids problems with unconsistent use of
 *  JSpinner font for the JFormattedTextField.
 * @since 2.0
 */
public class JaxoFixedJSpinner extends JSpinner {
    private static final long serialVersionUID = 7526471155622776147L;
    private Font textFieldFont;

    /** Constructor: just calls super(m).
     * @param m The initial SpinnerModel.
     */
    public JaxoFixedJSpinner(final SpinnerModel m) {
        super(m);
    }

    /** {@inheritDoc} */
    @Override
    public void setFont(final Font font) {
        final Font oldTextFieldFont = textFieldFont;

        // produce non-UIResource font so that JTextField.updateUI does
        // not override it
        textFieldFont =
            (font == null) ? null
                            : font.deriveFont(1f).deriveFont((float) font
                .getSize());

        super.setFont(font);

        if (getEditor() instanceof DefaultEditor) {
            final JTextField t = ((DefaultEditor) getEditor()).getTextField();
            if (t == null) {
                return;
            }

            if (hasFont(t, oldTextFieldFont)
                    || t.getFont() instanceof UIResource) {
                t.setFont(textFieldFont);
            }
        }
    }

    /** {@inheritDoc} */
    @Override
    public void setEditor(final JComponent editor) {
        if (editor == getEditor()) {
            return;
        }

        super.setEditor(editor);

        if (getEditor() instanceof DefaultEditor) {
            final JTextField t = ((DefaultEditor) getEditor()).getTextField();
            if (t == null) {
                return;
            }

            // if setEditor has installed the spinner font on the new text field,
            // replace it by the copy
            if (hasFont(t, getFont())) {
                t.setFont(textFieldFont);
            }
        }
    }

    private static boolean hasFont(final Component c, final Font f) {
        return (f == null) ? (!c.isFontSet())
                           : (c.isFontSet() && c.getFont().equals(f));
    }
}
