在我键入时替换 jTextField 的 0

Replace 0s of jTextField as I type

我想要带有 12 个 0 的 jTextField,我需要将这些 0 更改为我在键入时键入的数字。

我在 KeyPressed 活动中完成了此操作,但它无法正常工作。

  try {
        int i = Integer.parseInt(jTextField1.getText());
        jTextField1.setText(String.format("%012d", i));
    } catch (Exception e) {
        jTextField1.setText(String.format("%012d", 0));
    }
}             

它会随着我的输入而变化,但几乎没有问题。

  1. 直到我输入 11 个数字,它会改变,在我输入第 12 个数字后,它会删除所有数字并再次显示为 000000000005(如果我输入的第 12 个数字是 5)
  2. 当我全部删除时它只显示 10 个 0 而不是 12,但是当我再次输入一个数字时它显示输入的数字和 11 个 0。

有什么解决办法吗?

String result = text.substring(1) + inputKey;

这将排除左侧字符并添加新字符。

您的整数值可能已达到最大值,请尝试仅使用字符串。

    try {
        String i = jTextField1.getText();
        String text = "";
        for (int j = 0; j < (12 - i.length()); j++) {
            text += "0";
        }
        jTextField1.setText(text + i);
    } catch (Exception e) {
        jTextField1.setText(String.format("%012d", 0));
    }

或者,如果您希望它更短,您可以这样做。

    try {
        String i = jTextField1.getText();
        String text = "000000000000";
        jTextField1.setText(text.substring(0, (12-i.length())) + i );
    } catch (Exception e) {
        jTextField1.setText(String.format("%012d", 0));
    }

它只是根据文本字段的长度对 12 个 0 的字符串进行子字符串化,然后将其添加到末尾。

这是一个自定义 class,它试图模拟银行机器的数据输入。即文本从右到左输入:

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

public class ABMTextField extends JTextField
{
    private DecimalFormat format;
    private String decimal;

    public ABMTextField(DecimalFormat format)
    {
        this.format = format;

        decimal = Character.toString( format.getDecimalFormatSymbols().getDecimalSeparator() );

        setColumns( format.toPattern().length() );
        setHorizontalAlignment(JFormattedTextField.TRAILING);

        setText( format.format(0.0) );

        AbstractDocument doc = (AbstractDocument)getDocument();
        doc.setDocumentFilter( new ABMFilter() );
    }

    @Override
    public void setText(String text)
    {
        Number number = format.parse(text, new ParsePosition(0));

        if (number != null)
            super.setText( text );
    }

    public class ABMFilter extends DocumentFilter
    {
        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
            throws BadLocationException
        {
            replace(fb, offs, 0, str, a);
        }

        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
            throws BadLocationException
        {
            if (".0123456789".contains(str))
            {
                Document doc = fb.getDocument();
                StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) );

                int decimalOffset = sb.indexOf( decimal );

                if (decimalOffset != -1)
                {
                    sb.deleteCharAt(decimalOffset);
                    sb.insert(decimalOffset + 1, decimal);
                }

                sb.append(str);

                try
                {
                    String text = format.format( format.parse( sb.toString() ) );
                    super.replace(fb, 0, doc.getLength(), text, a);
                }
                catch(ParseException e) {}
            }
            else
                Toolkit.getDefaultToolkit().beep();
        }

        public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
            throws BadLocationException
        {
            Document doc = fb.getDocument();
            StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) );

            int decimalOffset = sb.indexOf( decimal );

            if (decimalOffset != -1)
            {
                sb.deleteCharAt(decimalOffset);
                sb.insert(decimalOffset - 1, decimal);
            }

            sb.deleteCharAt( sb.length() - 1) ;

            try
            {
                String text = format.format( format.parse( sb.toString() ) );
                super.replace(fb, 0, doc.getLength(), text, null);
            }
            catch(ParseException e) {}
        }
    }

    private static void createAndShowUI()
    {
//      DecimalFormat format = new DecimalFormat("###,##0.00");
        DecimalFormat format = new DecimalFormat("0000000000");
        ABMTextField abm = new ABMTextField( format );

        JPanel panel = new JPanel();
        panel.add( abm );

        JFrame frame = new JFrame("ABMTextField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setSize(200, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

您可以按如下方式更改默认掩码:

//DecimalFormat format = new DecimalFormat("###,##0.00");
DecimalFormat format = new DecimalFormat("0000000000");