java - 用于负整数和正整数的 DocumentFilter

标签 java swing jtextfield negative-number documentfilter

我知道这是一个常见问题,但我正在尝试创建一个只接受 int 数字的 TextField,这几乎完成了,这是代码:

创建文本框:

nome = new JFormattedTextField();
            nome.setHorizontalAlignment(SwingConstants.CENTER);
            nome.setColumns(2);

            DocumentFilter filtro = new FiltroNumero();
            ((AbstractDocument) nome.getDocument()).setDocumentFilter(filtro);

            panel.add(nome);

文档过滤器:

public class FiltroNumero extends DocumentFilter{

    public void insertString(DocumentFilter.FilterBypass fb, int offset, int length,
              String text, javax.swing.text.AttributeSet attr)

              throws BadLocationException {
                    fb.insertString(offset, text.replaceAll("[^-0-9]", ""), attr);
         }  
}

有了这个,TextField 将只接受数字和“-”,但这意味着“1-”是一个可能的值。

我需要的是一种使文本字段不接受第一个字符后的减号的方法。

如果有人能帮助我,我会很高兴:)

最佳答案

您可以简单地从 Document(替换之前)中获取整个文本,然后从该文档文本创建一个新的 String,添加 text 参数。然后只需检查匹配整数(负数或正数)的完整正则表达式。如果匹配,则进行替换。像这样的东西:

@Override
public void replace(FilterBypass fb, int offs, int length,
        String str, AttributeSet a) throws BadLocationException {

    String text = fb.getDocument().getText(0,
            fb.getDocument().getLength());

    StringBuilder builder = new StringBuilder(text);
    builder.insert(offs, str);
    String newText = builder.toString();

    // check
    System.out.println("text = " + text 
                   + ", offset = " + offs 
                   + ", newText = " + newText);

    if (newText.matches("(-)?\\d*")) {
        super.replace(fb, offs, length, str, a);
    } else {
        Toolkit.getDefaultToolkit().beep();
    }
}

注意:您应该使用 replace 而不是 insertString,尽管覆盖两者也无妨。

这是一个完整的演示

import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class FilterDemo {

    public FilterDemo() {
        JFrame frame = new JFrame();
        frame.add(createFilteredField());
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

    }

    private  JTextField createFilteredField() {
        JTextField field = new JTextField(10);
        AbstractDocument document = (AbstractDocument) field.getDocument();
        document.setDocumentFilter(new DocumentFilter() {

            @Override
            public void replace(FilterBypass fb, int offs, int length,
                    String str, AttributeSet a) throws BadLocationException {

                String text = fb.getDocument().getText(0,
                        fb.getDocument().getLength());

                StringBuilder builder = new StringBuilder(text);
                builder.insert(offs, str);
                String newText = builder.toString();

                // check
                System.out.println("text = " + text 
                               + ", offset = " + offs 
                               + ", newText = " + newText);

                if (newText.matches("(-)?\\d*")) {
                    super.replace(fb, offs, length, str, a);
                } else {
                    Toolkit.getDefaultToolkit().beep();
                }
            }


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

                String text = fb.getDocument().getText(0,
                        fb.getDocument().getLength());

                StringBuilder builder = new StringBuilder(text);
                builder.insert(offs, str);
                String newText = builder.toString();

                // checks
                System.out.println("text = " + text 
                               + ", offset = " + offs 
                               + ", newText = " + newText);

                if (newText.matches("(-)?\\d*")) {
                    super.insertString(fb, offs, str, a);
                } else {
                    Toolkit.getDefaultToolkit().beep();
                }
            } 
        });
        return field;
    }

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

关于java - 用于负整数和正整数的 DocumentFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520487/

相关文章:

java - 在 "firstUse"之后 onCreate 报告的 Android 首选项设置不一致——我的错,但是怎么样?

java - 我可以运行存储在 apk 中的脚本吗?

java - 多行 JTable 单元格在编辑期间不是多行的

java - 无法从 MigLayout 底部删除多余的行

java - 设置 JTextField 自动更改

java - lucene 不区分大小写的排序搜索

java - 一行输入

java - JGoodies FormLayout 拒绝调整我的 JComboBox 大小

java - 限制数字输入 JTextField

Java 将默认禁用的文本字段文本设置为黑色而不是灰色