正负整数的DocumentFilter [英] DocumentFilter for negative and positive integer

查看:77
本文介绍了正负整数的DocumentFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个常见问题,但是我正在尝试创建一个仅接受整数的TextField,并且差不多完成了,这是代码:

I know this is a common question, but I'm trying to create a TextField that only accept int numbers, and it's almost done, here's the code:

创建文本字段:

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

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

            panel.add(nome);

DocummentFilter:

DocummentFilter:

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-"是可能的值.

With this, the TextField will only accept numbers and "-", but it means that "1-" is a possible value.

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

What I need is a way to make the textfield don't accept the minus after the first character.

如果有人可以帮助我,我将非常高兴:)

If someone can help me, I'll be really glad :)

推荐答案

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

You could simply get the entire text from the Document (which is the before replace), then create a new String from that document text, adding the text argument. Then just check against a complete regex that matches integers (negative or positive). If it matches, then do the replace. Something like:

@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,尽管这对覆盖两者均无害.

Note: you should be using replace rather than insertString, though doesn't hurt to override both.

这是一个完整的演示

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();
            }
        });
    }
}

这篇关于正负整数的DocumentFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆