¿Cómo puedo lograr un JFormattextfield aceptar sólo el número y el carácter limitado

Nadim:

Tengo dos JFormattedTextFieldde las variables cantidad y la cuenta no.
propósito :

  1. Tanto campo debe aceptar solamente el número
  2. Acc No se puede tomar hasta 15 caracteres que pueden variar 8-15. Del mismo modo importe puede tener hasta 6 caracteres y también varía.

Para lograr esto he utilizado MaskFormatter, pero el problema es la "variación". Algunos acc es de 15 dígitos, algunos son 12 dígitos por lo que durante el uso MaskFormatterse limita a 15, se convierte en obligatoria para introducir datos insertados 15 dígitos de lo contrario desaparece durante el tiempo de ejecución cuando dejamos elJFormattedTextField

¿Hay alguna manera de obtener a la vez escenario en el swing de Java?
Por favor, me sugieren

camickr:

Utilice una DocumentFilter. A continuación, puede personalizar el filtro para sus requerimientos específicos.

Un ejemplo básico para empezar:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class DigitFilter extends DocumentFilter
{
    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
        throws BadLocationException
    {
        replace(fb, offset, 0, text, attributes);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attributes)
        throws BadLocationException
    {
        Document doc = fb.getDocument();

        // add check here check the length of the text currently in the document
        // with the length of your text String to make sure the total is not above the maximum
        // you should modify the class to pass a paramenter when you create the class for the
        // maximum length so the class can be reused

        if (isDigit( text ))
            super.replace(fb, offset, length, text, attributes);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    private boolean isDigit(String text)
    {
        for (int i = 0; i < text.length(); i++)
        {
            if (! Character.isDigit( text.charAt(i) ) )
                return false;
        }

        return true;
    }

    private static void createAndShowGUI()
    {
        JTextField textField = new JTextField(15);
        AbstractDocument doc = (AbstractDocument) textField.getDocument();
        doc.setDocumentFilter( new DigitFilter() );

        JFrame frame = new JFrame("Integer Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( textField );
        frame.setSize(220, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }

}

Usted tendrá que añadir la lógica separada (externo al DocumentFilter) para asegurarse de que la longitud de cuenta es al menos 8 dígitos antes de hacer su procesamiento.

Lea la sección del tutorial Swing en La implementación de un filtro de documentos para un ejemplo de un filtro que limita el número de caracteres. La lógica de allí necesita ser combinada con el ejemplo aquí.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=318925&siteId=1
Recomendado
Clasificación