[RESOLVIDO]Formatar Monetário no Swing

Pessoal, depois de tanto procurar por classes e/ou métodos que formatem os valores, pro formato R$, em um campo de texto e conseguir exemplos que não funcionem direito e ver o pessoal sempre rodar e não chegar à um denominador comum. Decidi vir até pedir a ajuda de vocês que já utilizaram, já passaram por essa dificuldade, como encontraram a solução? Realmente é necessário inventar a roda?

eu particularmente, criei um componente q transforma meus campos de textos , em campos formatados

package elite.core.se.component;

import elite.core.se.app.Application;
import elite.core.util.FieldType;
import elite.core.util.Tools;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class DynamicFieldExtender implements KeyListener, FocusListener {

    public static boolean UPPER_CASE = true;
    public static final int[] validKeyCode = {
        KeyEvent.VK_ESCAPE,
        KeyEvent.VK_BACK_SPACE,
        KeyEvent.VK_DELETE,
        KeyEvent.VK_ENTER,
        KeyEvent.VK_END,
        KeyEvent.VK_HOME,
        KeyEvent.VK_LEFT,
        KeyEvent.VK_RIGHT,
        KeyEvent.VK_SHIFT,
        KeyEvent.VK_CONTROL
    };
    private JFormattedTextField textField;
    private FieldType fieldType = FieldType.STRING;
    private int fieldPrecision = 0;
    private int fieldMaxSize = 255;

    public DynamicFieldExtender init() {
        
        
        textField.addKeyListener(this);
        textField.addFocusListener(this);
        textField.setDocument(new ExtendedDocument(fieldMaxSize, UPPER_CASE));

        if (fieldType.name().startsWith("MASK_") && fieldType != FieldType.MASK_CNPJ_CPF) {
            setMask(fieldType.getMask());
        }

        formatTextExit();

        return this;
    }

    public void setEmptyFloat() {
        String fmt = "";
        fmt = "%,." + ((Integer) fieldPrecision).toString() + "f";
        textField.setText(String.format(fmt, 0.0f));
    }

    public void setEmptyDate() {
        textField.setText("  /  /    ");
    }

    public void setMask(String mask) {
        try {
            String oldValue = textField.getText();
            textField.setText("");
            MaskFormatter maskForm = new MaskFormatter(mask);
            maskForm.setValueContainsLiteralCharacters(false);
            if (fieldType.equals(FieldType.MASK_PLACA)) {
                maskForm.setValidCharacters("qwertyuiopasdfghjklzxcvbnm0123456789 ");
            } else {
                maskForm.setValidCharacters("0123456789 ");
            }
            maskForm.setPlaceholderCharacter(' ');
            textField.setFormatterFactory(new DefaultFormatterFactory(maskForm));


            textField.setText(oldValue);
        } catch (Exception ex) {
        }
    }

    public void formatTextEnter() {
        switch (fieldType) {
            case DATE:

                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
                textField.selectAll();

                break;
            case FLOAT:
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyFloatNumber(textField.getText()));
                textField.selectAll();

                if (textField.isEditable()) {
                    textField.setHorizontalAlignment(SwingConstants.LEFT);
                }
                break;
            case INTEGER:
            case NUMBER_STRING:
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
                textField.selectAll();
                textField.setHorizontalAlignment(SwingConstants.LEFT);
                break;
            case STRING:
                if (textField.getFormatter() != null) {
                    textField.selectAll();
                }
                break;
        }

        if (fieldType.name().startsWith("MASK_")) {
            if (fieldType.equals(FieldType.MASK_CNPJ_CPF)) {
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
            }

            textField.selectAll();
        }
    }

    public void formatTextExit() {
        switch (fieldType) {
            case DATE:
                String txt = textField.getText();

                if (txt.equals("  /  /    ")) {
                    return;
                }

                if (txt.equals("h") || txt.equals("H")) {
                    txt = Tools.onlyNumber((new SimpleDateFormat("dd/MM/yyyy")).format(new Date()));
                }

                if (txt.startsWith("+") || txt.startsWith("-")) {
                    try {
                        int qtdDia = Integer.parseInt(txt.substring(1, txt.length()));
                        Calendar data = Calendar.getInstance();
                        if (txt.startsWith("+")) {
                            data.add(Calendar.DAY_OF_MONTH, qtdDia);
                        }
                        if (txt.startsWith("-")) {
                            data.add(Calendar.DAY_OF_MONTH, qtdDia * -1);
                        }
                        txt = Tools.onlyNumber((new SimpleDateFormat("dd/MM/yyyy")).format(data.getTime()));
                    } catch (Exception ex) {
                        txt = "";
                    }
                }

                MaskFormatter mask = null;

                if (txt.length() >= 5 && txt.length() <= 7) {
                    String ano = txt.substring(4, txt.length());
                    Integer iano = Integer.parseInt(ano) + 2000;
                    txt = txt.substring(0, 4) + iano.toString();
                }

                try {
                    mask = new MaskFormatter("##/##/####");
                    mask.setPlaceholderCharacter(' ');
                } catch (Exception ex) {
                }

                textField.setFormatterFactory(new DefaultFormatterFactory(mask));
                textField.setText(txt);

                try {
                    Date dt = (new SimpleDateFormat("dd/MM/yyyy")).parse(textField.getText());
                    textField.setText((new SimpleDateFormat("dd/MM/yyyy")).format(dt));
                } catch (Exception ex) {
                    textField.setText("");
                }

                break;
            case FLOAT:
                String signal = "";

                if (textField.getText().startsWith("-")) {
                    signal = "-";
                }
                
                if (DecimalFormatSymbols.getInstance().getDecimalSeparator() == ',') {
                    textField.setText(Tools.onlyFloatNumber(textField.getText()).replace(",", "."));
                }
                
                String fmt = "";
                fmt = "%,." + ((Integer) fieldPrecision).toString() + "f";
                try {
                    textField.setText(signal + String.format(fmt, Double.parseDouble(textField.getText())));
                } catch (Exception ex) {
                    setEmptyFloat();
                }

                if (textField.isEditable()) {
                    textField.setHorizontalAlignment(SwingConstants.RIGHT);
                }

                break;

            case MASK_CNPJ_CPF:
                if (textField.getText().length() == 11) {
                    setMask(FieldType.MASK_CPF.getMask());
                } else if (textField.getText().length() == 14) {
                    setMask(FieldType.MASK_CNPJ.getMask());
                } else {
                    textField.setText("");
                }

                break;
            case INTEGER:
            case NUMBER_STRING:
                textField.setHorizontalAlignment(SwingConstants.RIGHT);
                break;
        }
    }

    public DynamicFieldExtender() {
    }

    public DynamicFieldExtender(JFormattedTextField textField) {
        this.setTextField(textField);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType) {
        this(textField);
        this.setFieldType(fieldType);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType, int fieldPrecision) {
        this(textField, fieldType);
        this.setFieldPrecision(fieldPrecision);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType, int fieldPrecision, int fieldMaxSize) {
        this(textField, fieldType, fieldPrecision);
        this.setFieldMaxSize(fieldMaxSize);
    }

    public FieldType getFieldType() {
        return fieldType;
    }

    public DynamicFieldExtender setFieldType(FieldType fieldType) {
        if (fieldType.equals(FieldType.FLOAT) && fieldPrecision == 0) {
            fieldPrecision = 2;
        }

        this.fieldType = fieldType;

        return this;
    }

    public JFormattedTextField getTextField() {
        return textField;
    }

    public DynamicFieldExtender setTextField(JFormattedTextField textField) {
        this.textField = textField;
        return this;
    }

    public int getFieldPrecision() {
        return fieldPrecision;
    }

    public DynamicFieldExtender setFieldPrecision(int fieldPrecision) {
        this.fieldPrecision = fieldPrecision;
        return this;
    }

    public int getFieldMaxSize() {
        return fieldMaxSize;
    }

    public DynamicFieldExtender setFieldMaxSize(int fieldMaxSize) {
        this.fieldMaxSize = fieldMaxSize;
        return this;
    }

    private boolean isValidKeyCode(KeyEvent e) {
        final int keyCode = e.getKeyCode();
        for (int key : validKeyCode) {
            if (key == keyCode) {
                return true;
            }
        }
        return false;
    }

    private Boolean containsStr(String[] strList) {
        for (String str : strList) {
            if (textField.getText().toUpperCase().contains(str)) {
                return true;
            }
        }

        return false;
    }

    protected void processKeyEvent(KeyEvent e) {
        if ((fieldType.equals(FieldType.DATE) || fieldType.equals(FieldType.INTEGER) || fieldType.equals(FieldType.NUMBER_STRING) || fieldType.equals(FieldType.FLOAT) || fieldType.equals(FieldType.MASK_CNPJ_CPF))
                && !isValidKeyCode(e)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_C)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_V)
                && !(fieldType.equals(FieldType.DATE) && (e.getKeyChar() == 'H' || e.getKeyChar() == 'h') && !containsStr(new String[]{
                    "H", "+", "-"
                }))
                && !(fieldType.equals(FieldType.DATE) && e.getKeyChar() == '+' && !containsStr(new String[]{
                    "H", "+", "-"
                }))
                && !(fieldType.equals(FieldType.DATE) && e.getKeyChar() == '-' && !containsStr(new String[]{
                    "H", "+", "-"
                }))) {

            String validChars = "";

            switch (fieldType) {
                case DATE:
                case MASK_CNPJ_CPF:
                    validChars = "1234567890";
                    break;
                case FLOAT:
                    validChars = "1234567890";
                    if (fieldPrecision > 0) {
                        validChars += DecimalFormatSymbols.getInstance().getDecimalSeparator();
                    }
                    break;
                case INTEGER:
                case NUMBER_STRING:
                    validChars = "1234567890";
                    break;
            }

            if ((validChars.indexOf(e.getKeyChar()) < 0)
                    || ((e.getKeyChar() == DecimalFormatSymbols.getInstance().getDecimalSeparator()) && (textField.getText().indexOf(DecimalFormatSymbols.getInstance().getDecimalSeparator()) > 0))) {
                e.consume();
            }
        }
    }

    public void keyTyped(KeyEvent e) {
        processKeyEvent(e);
    }

    public void keyPressed(KeyEvent e) {
        processKeyEvent(e);
    }

    public void keyReleased(KeyEvent e) {
        processKeyEvent(e);
    }

    public void focusGained(FocusEvent e) {
        formatTextEnter();
    }

    public void focusLost(FocusEvent e) {
        if (fieldType == FieldType.STRING) {
            if (textField.getFormatter() != null) {
                ((MaskFormatter) textField.getFormatter()).setPlaceholder(textField.getText());

                if (textField.getText().length() != textField.getText().trim().length()) {
                    textField.setValue("");
                }
            }
        }

        formatTextExit();
    }

    public Double getAsFloat() {
        if (textField.getText().equals("")) {
            return 0.0;
        }

        return Double.parseDouble(Tools.onlyFloatNumber(textField.getText()).replace(",", "."));
    }

    public Integer getAsInteger() {
        if (textField.getText().equals("")) {
            return 0;
        }

        return Integer.parseInt(Tools.onlyNumber(textField.getText()));
    }

    public Date getAsDate() {
        if (textField.getText().substring(0, 1).equals(" ")) {
            return null;
        }

        try {
            switch (fieldType) {
                case DATE:
                    if (textField.hasFocus()) {
                        return (new SimpleDateFormat("ddMMyyyy")).parse(textField.getText());
                    } else {
                        return (new SimpleDateFormat("dd/MM/yyyy")).parse(textField.getText());
                    }
                case TIME:
                    return (new SimpleDateFormat("HH:mm")).parse(textField.getText());
            }

            return null;
        } catch (Exception ex) {
            return null;
        }
    }

    public String getAsString() {
        if (fieldType.name().startsWith("MASK_")) {
            try {
                textField.commitEdit();
            } catch (Exception ex) {
                Application.exception(ex);
            }
            if (textField.getValue() == null) {
                return null;
            }

            return textField.getValue().toString();
        } else {
            return textField.getText();
        }
    }

    public Object getValue() {

        switch (fieldType) {
            case DATE:
                return getAsDate();
            case TIME:
                return getAsDate();
            case INTEGER:
                return getAsInteger();
            case FLOAT:
                if (fieldPrecision == 0) {
                    return getAsInteger();
                }

                return getAsFloat();
        }

        return getAsString();
    }

    public DynamicFieldExtender setValue(Object value) {
        resetValue();

        if (value != null) {
            try {
                switch (fieldType) {
                    case DATE:
                        textField.setText((new SimpleDateFormat("dd/MM/yyyy")).format((Date) value));
                        break;
                    case TIME:
                        textField.setText((new SimpleDateFormat("HH:mm")).format((Date) value));
                        break;
                    case FLOAT:
                        if (value instanceof Integer) {
                            textField.setText(((Integer) value).toString());
                        } else if (value instanceof Double) {
                            if (DecimalFormatSymbols.getInstance().getDecimalSeparator() == ',') {
                                textField.setText(((Double) value).toString().replace(".", ","));
                            } else {
                                textField.setText(((Double) value).toString());
                            }
                                
                        } else {
                            textField.setText(Tools.onlyFloatNumber(value.toString()));
                        }
                        break;
                    case INTEGER:
                        if (value instanceof Integer) {
                            textField.setText(((Integer) value).toString());
                        } else {
                            textField.setText(Tools.onlyNumber(value.toString()));
                        }


                        break;
                    case MASK_CNPJ_CPF:
                        textField.setFormatterFactory(null);
                        textField.setText((String) value);
                    default:
                        textField.setText((String) value);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                textField.setText("");
            }
        }

        formatTextExit();

        return this;
    }

    public DynamicFieldExtender resetValue() {
        textField.setText("");
        formatTextExit();
        return this;
    }

    public boolean isNull() {
        try {
            switch (fieldType) {
                case DATE:
                    return getValue() == null;
                case FLOAT:
                case INTEGER:
                    return getValue() == null || getValue().equals(0);
                default:
                    return getValue() == null || textField.getText().trim().equals("");
            }
        } catch (Exception ex) {
            return false;
        }
    }
}

ai tem algumas funcoes da class elite.core.util.Tools

public static String onlyNumber(String val) {
        return val.replaceAll("[^0-9]", "");
    }

    public static String onlyFloatNumber(String val) {
        return val.replaceAll("[^0-9" + DecimalFormatSymbols.getInstance().getDecimalSeparator() + "]", "");
    }

e tambem da elite.core.util.FieldType

package elite.core.util;

public enum FieldType
{
    STRING, INTEGER, FLOAT, DATE, TIME, NUMBER_STRING,
    MASK_CNPJ, MASK_CPF, MASK_CNPJ_CPF, MASK_FONE, MASK_PLACA, MASK_CEP;
    
    public String getMask()
    {
        switch (this)
        {
            
            case MASK_CNPJ: return "**.***.***/****-**";
            case MASK_CPF: return "***.***.***-**";
            case MASK_FONE: return "(**) ****-****";
            case MASK_PLACA: return "***-****";
            case MASK_CEP: return "*****-***";
//            case MASK_CNPJ: return "##.###.###/####-##";
//            case MASK_CPF: return "###.###.###-##";
//            case MASK_FONE: return "(##) ####-####";
//            case MASK_PLACA: return "AAA-####";
//            case MASK_CEP: return "#####-###";
        }
        
        return null;
    }
    
    public boolean is(FieldType ... fieldTypes)
    {
        for (FieldType fieldType: fieldTypes)
        {
            if (this.equals(fieldType))
                return true;
        }
        
        return false;
    }
    
    public boolean isString()
    {
        return this.is(STRING, MASK_CNPJ, MASK_CPF, MASK_CNPJ_CPF, MASK_FONE, MASK_PLACA, MASK_CEP);
    }
}

substitua tb a Application.exception(ex); por num throw , ou algo do tipo, siga a ideia ai, se nao conseguir fazer funcionar , posta ai

essa classe serve pra campos tipos data, numeros, maskaras e td + tudo em um so … com algumas funcionalidades
ex, se vc digitar H num campo data, ele coloca a data do dia, +1 ele coloca a data do dia + 1, -1 o dia -1
em campos numericos mesma coisa, como se fosse uma calculadora

[quote=shinoob]eu particularmente, criei um componente q transforma meus campos de textos , em campos formatados

package elite.core.se.component;

import elite.core.se.app.Application;
import elite.core.util.FieldType;
import elite.core.util.Tools;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class DynamicFieldExtender implements KeyListener, FocusListener {

    public static boolean UPPER_CASE = true;
    public static final int[] validKeyCode = {
        KeyEvent.VK_ESCAPE,
        KeyEvent.VK_BACK_SPACE,
        KeyEvent.VK_DELETE,
        KeyEvent.VK_ENTER,
        KeyEvent.VK_END,
        KeyEvent.VK_HOME,
        KeyEvent.VK_LEFT,
        KeyEvent.VK_RIGHT,
        KeyEvent.VK_SHIFT,
        KeyEvent.VK_CONTROL
    };
    private JFormattedTextField textField;
    private FieldType fieldType = FieldType.STRING;
    private int fieldPrecision = 0;
    private int fieldMaxSize = 255;

    public DynamicFieldExtender init() {
        
        
        textField.addKeyListener(this);
        textField.addFocusListener(this);
        textField.setDocument(new ExtendedDocument(fieldMaxSize, UPPER_CASE));

        if (fieldType.name().startsWith("MASK_") && fieldType != FieldType.MASK_CNPJ_CPF) {
            setMask(fieldType.getMask());
        }

        formatTextExit();

        return this;
    }

    public void setEmptyFloat() {
        String fmt = "";
        fmt = "%,." + ((Integer) fieldPrecision).toString() + "f";
        textField.setText(String.format(fmt, 0.0f));
    }

    public void setEmptyDate() {
        textField.setText("  /  /    ");
    }

    public void setMask(String mask) {
        try {
            String oldValue = textField.getText();
            textField.setText("");
            MaskFormatter maskForm = new MaskFormatter(mask);
            maskForm.setValueContainsLiteralCharacters(false);
            if (fieldType.equals(FieldType.MASK_PLACA)) {
                maskForm.setValidCharacters("qwertyuiopasdfghjklzxcvbnm0123456789 ");
            } else {
                maskForm.setValidCharacters("0123456789 ");
            }
            maskForm.setPlaceholderCharacter(' ');
            textField.setFormatterFactory(new DefaultFormatterFactory(maskForm));


            textField.setText(oldValue);
        } catch (Exception ex) {
        }
    }

    public void formatTextEnter() {
        switch (fieldType) {
            case DATE:

                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
                textField.selectAll();

                break;
            case FLOAT:
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyFloatNumber(textField.getText()));
                textField.selectAll();

                if (textField.isEditable()) {
                    textField.setHorizontalAlignment(SwingConstants.LEFT);
                }
                break;
            case INTEGER:
            case NUMBER_STRING:
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
                textField.selectAll();
                textField.setHorizontalAlignment(SwingConstants.LEFT);
                break;
            case STRING:
                if (textField.getFormatter() != null) {
                    textField.selectAll();
                }
                break;
        }

        if (fieldType.name().startsWith("MASK_")) {
            if (fieldType.equals(FieldType.MASK_CNPJ_CPF)) {
                textField.setFormatterFactory(null);
                textField.setText(Tools.onlyNumber(textField.getText()));
            }

            textField.selectAll();
        }
    }

    public void formatTextExit() {
        switch (fieldType) {
            case DATE:
                String txt = textField.getText();

                if (txt.equals("  /  /    ")) {
                    return;
                }

                if (txt.equals("h") || txt.equals("H")) {
                    txt = Tools.onlyNumber((new SimpleDateFormat("dd/MM/yyyy")).format(new Date()));
                }

                if (txt.startsWith("+") || txt.startsWith("-")) {
                    try {
                        int qtdDia = Integer.parseInt(txt.substring(1, txt.length()));
                        Calendar data = Calendar.getInstance();
                        if (txt.startsWith("+")) {
                            data.add(Calendar.DAY_OF_MONTH, qtdDia);
                        }
                        if (txt.startsWith("-")) {
                            data.add(Calendar.DAY_OF_MONTH, qtdDia * -1);
                        }
                        txt = Tools.onlyNumber((new SimpleDateFormat("dd/MM/yyyy")).format(data.getTime()));
                    } catch (Exception ex) {
                        txt = "";
                    }
                }

                MaskFormatter mask = null;

                if (txt.length() >= 5 && txt.length() <= 7) {
                    String ano = txt.substring(4, txt.length());
                    Integer iano = Integer.parseInt(ano) + 2000;
                    txt = txt.substring(0, 4) + iano.toString();
                }

                try {
                    mask = new MaskFormatter("##/##/####");
                    mask.setPlaceholderCharacter(' ');
                } catch (Exception ex) {
                }

                textField.setFormatterFactory(new DefaultFormatterFactory(mask));
                textField.setText(txt);

                try {
                    Date dt = (new SimpleDateFormat("dd/MM/yyyy")).parse(textField.getText());
                    textField.setText((new SimpleDateFormat("dd/MM/yyyy")).format(dt));
                } catch (Exception ex) {
                    textField.setText("");
                }

                break;
            case FLOAT:
                String signal = "";

                if (textField.getText().startsWith("-")) {
                    signal = "-";
                }
                
                if (DecimalFormatSymbols.getInstance().getDecimalSeparator() == ',') {
                    textField.setText(Tools.onlyFloatNumber(textField.getText()).replace(",", "."));
                }
                
                String fmt = "";
                fmt = "%,." + ((Integer) fieldPrecision).toString() + "f";
                try {
                    textField.setText(signal + String.format(fmt, Double.parseDouble(textField.getText())));
                } catch (Exception ex) {
                    setEmptyFloat();
                }

                if (textField.isEditable()) {
                    textField.setHorizontalAlignment(SwingConstants.RIGHT);
                }

                break;

            case MASK_CNPJ_CPF:
                if (textField.getText().length() == 11) {
                    setMask(FieldType.MASK_CPF.getMask());
                } else if (textField.getText().length() == 14) {
                    setMask(FieldType.MASK_CNPJ.getMask());
                } else {
                    textField.setText("");
                }

                break;
            case INTEGER:
            case NUMBER_STRING:
                textField.setHorizontalAlignment(SwingConstants.RIGHT);
                break;
        }
    }

    public DynamicFieldExtender() {
    }

    public DynamicFieldExtender(JFormattedTextField textField) {
        this.setTextField(textField);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType) {
        this(textField);
        this.setFieldType(fieldType);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType, int fieldPrecision) {
        this(textField, fieldType);
        this.setFieldPrecision(fieldPrecision);
    }

    public DynamicFieldExtender(JFormattedTextField textField, FieldType fieldType, int fieldPrecision, int fieldMaxSize) {
        this(textField, fieldType, fieldPrecision);
        this.setFieldMaxSize(fieldMaxSize);
    }

    public FieldType getFieldType() {
        return fieldType;
    }

    public DynamicFieldExtender setFieldType(FieldType fieldType) {
        if (fieldType.equals(FieldType.FLOAT) && fieldPrecision == 0) {
            fieldPrecision = 2;
        }

        this.fieldType = fieldType;

        return this;
    }

    public JFormattedTextField getTextField() {
        return textField;
    }

    public DynamicFieldExtender setTextField(JFormattedTextField textField) {
        this.textField = textField;
        return this;
    }

    public int getFieldPrecision() {
        return fieldPrecision;
    }

    public DynamicFieldExtender setFieldPrecision(int fieldPrecision) {
        this.fieldPrecision = fieldPrecision;
        return this;
    }

    public int getFieldMaxSize() {
        return fieldMaxSize;
    }

    public DynamicFieldExtender setFieldMaxSize(int fieldMaxSize) {
        this.fieldMaxSize = fieldMaxSize;
        return this;
    }

    private boolean isValidKeyCode(KeyEvent e) {
        final int keyCode = e.getKeyCode();
        for (int key : validKeyCode) {
            if (key == keyCode) {
                return true;
            }
        }
        return false;
    }

    private Boolean containsStr(String[] strList) {
        for (String str : strList) {
            if (textField.getText().toUpperCase().contains(str)) {
                return true;
            }
        }

        return false;
    }

    protected void processKeyEvent(KeyEvent e) {
        if ((fieldType.equals(FieldType.DATE) || fieldType.equals(FieldType.INTEGER) || fieldType.equals(FieldType.NUMBER_STRING) || fieldType.equals(FieldType.FLOAT) || fieldType.equals(FieldType.MASK_CNPJ_CPF))
                && !isValidKeyCode(e)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_C)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X)
                && !(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_V)
                && !(fieldType.equals(FieldType.DATE) && (e.getKeyChar() == 'H' || e.getKeyChar() == 'h') && !containsStr(new String[]{
                    "H", "+", "-"
                }))
                && !(fieldType.equals(FieldType.DATE) && e.getKeyChar() == '+' && !containsStr(new String[]{
                    "H", "+", "-"
                }))
                && !(fieldType.equals(FieldType.DATE) && e.getKeyChar() == '-' && !containsStr(new String[]{
                    "H", "+", "-"
                }))) {

            String validChars = "";

            switch (fieldType) {
                case DATE:
                case MASK_CNPJ_CPF:
                    validChars = "1234567890";
                    break;
                case FLOAT:
                    validChars = "1234567890";
                    if (fieldPrecision > 0) {
                        validChars += DecimalFormatSymbols.getInstance().getDecimalSeparator();
                    }
                    break;
                case INTEGER:
                case NUMBER_STRING:
                    validChars = "1234567890";
                    break;
            }

            if ((validChars.indexOf(e.getKeyChar()) < 0)
                    || ((e.getKeyChar() == DecimalFormatSymbols.getInstance().getDecimalSeparator()) && (textField.getText().indexOf(DecimalFormatSymbols.getInstance().getDecimalSeparator()) > 0))) {
                e.consume();
            }
        }
    }

    public void keyTyped(KeyEvent e) {
        processKeyEvent(e);
    }

    public void keyPressed(KeyEvent e) {
        processKeyEvent(e);
    }

    public void keyReleased(KeyEvent e) {
        processKeyEvent(e);
    }

    public void focusGained(FocusEvent e) {
        formatTextEnter();
    }

    public void focusLost(FocusEvent e) {
        if (fieldType == FieldType.STRING) {
            if (textField.getFormatter() != null) {
                ((MaskFormatter) textField.getFormatter()).setPlaceholder(textField.getText());

                if (textField.getText().length() != textField.getText().trim().length()) {
                    textField.setValue("");
                }
            }
        }

        formatTextExit();
    }

    public Double getAsFloat() {
        if (textField.getText().equals("")) {
            return 0.0;
        }

        return Double.parseDouble(Tools.onlyFloatNumber(textField.getText()).replace(",", "."));
    }

    public Integer getAsInteger() {
        if (textField.getText().equals("")) {
            return 0;
        }

        return Integer.parseInt(Tools.onlyNumber(textField.getText()));
    }

    public Date getAsDate() {
        if (textField.getText().substring(0, 1).equals(" ")) {
            return null;
        }

        try {
            switch (fieldType) {
                case DATE:
                    if (textField.hasFocus()) {
                        return (new SimpleDateFormat("ddMMyyyy")).parse(textField.getText());
                    } else {
                        return (new SimpleDateFormat("dd/MM/yyyy")).parse(textField.getText());
                    }
                case TIME:
                    return (new SimpleDateFormat("HH:mm")).parse(textField.getText());
            }

            return null;
        } catch (Exception ex) {
            return null;
        }
    }

    public String getAsString() {
        if (fieldType.name().startsWith("MASK_")) {
            try {
                textField.commitEdit();
            } catch (Exception ex) {
                Application.exception(ex);
            }
            if (textField.getValue() == null) {
                return null;
            }

            return textField.getValue().toString();
        } else {
            return textField.getText();
        }
    }

    public Object getValue() {

        switch (fieldType) {
            case DATE:
                return getAsDate();
            case TIME:
                return getAsDate();
            case INTEGER:
                return getAsInteger();
            case FLOAT:
                if (fieldPrecision == 0) {
                    return getAsInteger();
                }

                return getAsFloat();
        }

        return getAsString();
    }

    public DynamicFieldExtender setValue(Object value) {
        resetValue();

        if (value != null) {
            try {
                switch (fieldType) {
                    case DATE:
                        textField.setText((new SimpleDateFormat("dd/MM/yyyy")).format((Date) value));
                        break;
                    case TIME:
                        textField.setText((new SimpleDateFormat("HH:mm")).format((Date) value));
                        break;
                    case FLOAT:
                        if (value instanceof Integer) {
                            textField.setText(((Integer) value).toString());
                        } else if (value instanceof Double) {
                            if (DecimalFormatSymbols.getInstance().getDecimalSeparator() == ',') {
                                textField.setText(((Double) value).toString().replace(".", ","));
                            } else {
                                textField.setText(((Double) value).toString());
                            }
                                
                        } else {
                            textField.setText(Tools.onlyFloatNumber(value.toString()));
                        }
                        break;
                    case INTEGER:
                        if (value instanceof Integer) {
                            textField.setText(((Integer) value).toString());
                        } else {
                            textField.setText(Tools.onlyNumber(value.toString()));
                        }


                        break;
                    case MASK_CNPJ_CPF:
                        textField.setFormatterFactory(null);
                        textField.setText((String) value);
                    default:
                        textField.setText((String) value);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                textField.setText("");
            }
        }

        formatTextExit();

        return this;
    }

    public DynamicFieldExtender resetValue() {
        textField.setText("");
        formatTextExit();
        return this;
    }

    public boolean isNull() {
        try {
            switch (fieldType) {
                case DATE:
                    return getValue() == null;
                case FLOAT:
                case INTEGER:
                    return getValue() == null || getValue().equals(0);
                default:
                    return getValue() == null || textField.getText().trim().equals("");
            }
        } catch (Exception ex) {
            return false;
        }
    }
}

ai tem algumas funcoes da class elite.core.util.Tools

public static String onlyNumber(String val) {
        return val.replaceAll("[^0-9]", "");
    }

    public static String onlyFloatNumber(String val) {
        return val.replaceAll("[^0-9" + DecimalFormatSymbols.getInstance().getDecimalSeparator() + "]", "");
    }

e tambem da elite.core.util.FieldType

package elite.core.util;

public enum FieldType
{
    STRING, INTEGER, FLOAT, DATE, TIME, NUMBER_STRING,
    MASK_CNPJ, MASK_CPF, MASK_CNPJ_CPF, MASK_FONE, MASK_PLACA, MASK_CEP;
    
    public String getMask()
    {
        switch (this)
        {
            
            case MASK_CNPJ: return "**.***.***/****-**";
            case MASK_CPF: return "***.***.***-**";
            case MASK_FONE: return "(**) ****-****";
            case MASK_PLACA: return "***-****";
            case MASK_CEP: return "*****-***";
//            case MASK_CNPJ: return "##.###.###/####-##";
//            case MASK_CPF: return "###.###.###-##";
//            case MASK_FONE: return "(##) ####-####";
//            case MASK_PLACA: return "AAA-####";
//            case MASK_CEP: return "#####-###";
        }
        
        return null;
    }
    
    public boolean is(FieldType ... fieldTypes)
    {
        for (FieldType fieldType: fieldTypes)
        {
            if (this.equals(fieldType))
                return true;
        }
        
        return false;
    }
    
    public boolean isString()
    {
        return this.is(STRING, MASK_CNPJ, MASK_CPF, MASK_CNPJ_CPF, MASK_FONE, MASK_PLACA, MASK_CEP);
    }
}

substitua tb a Application.exception(ex); por num throw , ou algo do tipo, siga a ideia ai, se nao conseguir fazer funcionar , posta ai

essa classe serve pra campos tipos data, numeros, maskaras e td + tudo em um so … com algumas funcionalidades
ex, se vc digitar H num campo data, ele coloca a data do dia, +1 ele coloca a data do dia + 1, -1 o dia -1
em campos numericos mesma coisa, como se fosse uma calculadora[/quote]

Muito show, mais é um pouco desanimador trabalhar com swing, uma vez que pra mascarar um campo é necessário codificar tanto.
Mais ajudou bastante, irei utilizar nas demais mascaras que precisar, no entanto pra mascarar monetário, utilizei o PlainDocument abaixo:

[code]import javax.swing.text.*;

public class MaskMoedaDocument extends PlainDocument {

public static final int maxdigits = 12;  

    @Override  
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {  

    String texto = getText(0, getLength());  

    for (int i = 0; i < str.length(); i++) {  
        char c = str.charAt(i);  
        if (!Character.isDigit(c)) {  
            return;  
        }  
    }  

    if(texto.length() < MaskMoedaDocument.maxdigits){  
        super.remove(0, getLength());  
        texto = texto.replace(".", "").replace(",", "");  
        StringBuffer s = new StringBuffer(texto + str);  

        if (s.length() > 0 && s.charAt(0) == '0') {  
            s.deleteCharAt(0);  
        }  

        if(s.length() < 3) {  
            if (s.length() < 1) {  
                s.insert(0,"000");  
            } else if (s.length() < 2) {  
                s.insert(0,"00");  
            } else {  
                s.insert(0,"0");  
            }  
        }  

        s.insert(s.length()-2, ",");  

        if(s.length() > 6) {  
            s.insert(s.length()-6, ".");  
        }  

        if(s.length() > 10) {  
            s.insert(s.length()-10, ".");  
        }  

        super.insertString(0, s.toString(), a);  
    }  
}  

    @Override  
public void remove(int offset, int length) throws BadLocationException {  
    super.remove(offset, length);  
    String texto = getText(0, getLength());  
    texto = texto.replace(",", "");  
    texto = texto.replace(".", "");  
    super.remove(0, getLength());  
    insertString(0, texto, null);  
}  

} [/code]

é … mas é q esse meu codigo ai faz mta coisa de uma vez so, vc coloca um JFormatedText, e ele serve pra campos de datas, numeros, maskaras e tem umas funcionalidades a +
como pegar o valor ja em Double ou Date, ja convertido pra vc fora as demais funcionalidade q eu ja citei
e outra coisa, vc nao pode pensar em qunatidade de codificacao, mas sim , em reutilizacao
uma vez feito isso, vc cria uma biblioteca, e usa em outros projetos
ao menos é o q eu faço … ja uso esse mesmo codigo em muitos outros projetos, :wink: