有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

显示可编辑整数数组的java最佳格式化程序?(可能以0开头)

我使用JFormattedTextField作为其容器。我不知道如何使用NumberFormatter,它会将所有内容转换为int,所以。。是 啊也不能用MaskFormatter实现,它强制输入与原始掩码匹配,在我的例子中是8位(“#######”)。任何位数(最多8位)都可以。请帮忙

编辑:

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    "Yes, allows only numbers, even those with 0 as first character, and with a size of max 8"

    只需使用^{}(对于文本字段的底层文档)过滤掉不是数字的任何内容,也可以过滤掉导致文本字段文档长度超过8的任何内容

    这里有一个例子

    import java.awt.GridLayout;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class TestFieldToArray {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    final JTextField field = getFilteredField();
                    final JTextField field2 = getFilteredField();
                    JPanel panel = new JPanel(new GridLayout(0, 1));
                    panel.add(field);
                    panel.add(field2);
                    JOptionPane.showMessageDialog(null, panel);
                }
            }); 
        }
    
        static JTextField getFilteredField() {
            JTextField field = new JTextField(15);
            AbstractDocument doc = (AbstractDocument) field.getDocument();
            doc.setDocumentFilter(new DocumentFilter() {
    
                private final int maxChars = 8;
    
                @Override
                public void replace(FilterBypass fb, int offs, int length,
                        String str, AttributeSet a) throws BadLocationException {
                    int docLength = fb.getDocument().getLength();
                    if (docLength < maxChars) {
                    super.replace(fb, offs, length,
                            str.replaceAll("[^0-9]+", ""), a);
                    }
                }
    
                @Override
                public void insertString(FilterBypass fb, int offs, String str,
                        AttributeSet a) throws BadLocationException {
                    int docLength = fb.getDocument().getLength();
                    if (docLength < maxChars) {
                        super.insertString(fb, offs,
                                str.replaceAll("[^0-9]+", ""), a);
                    }        
                }
            });
            return field;
        }
    }