只允许将数字和符号( - )输入JTextField [英] Only allowing numbers and a symbol (-) to be typed into a JTextField

查看:153
本文介绍了只允许将数字和符号( - )输入JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个数学测验,我只希望用户能够输入数字,无论它们是负数还是正数。有没有办法这样做?我曾经想过使用正则表达式,但我听说它们使用起来很糟糕。我尝试使用keylistener,但如果用户粘贴了怎么办?我已经尝试解析字符串以获得整数,但负符号将无效。

I'm trying to create a math quiz and I only want the user to be able to enter numbers whether they're negative or positive. Is there any way to do so? I've thought of using Regular Expressions but I've heard that they are bad to use. I tried using a keylistener but then what if the user pastes? I've tried parsing the string to get an integer but then the negative symbol will not work.

任何想法?

package com.quiz.ui;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SSCCE {

    private JFrame frame;

    private JPanel contentPane;

    private JTextField usernameField;

    public static void main(String[] arguments) {
        new SSCCE().construct();
    }

    public void construct() {
        frame = new JFrame("Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    public JPanel getContentPane() {
        usernameField = new JTextField(5);
        usernameField.addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent arg0) {
                int keyCode = arg0.getKeyCode();
                if ((keyCode > 47 && keyCode < 58) || keyCode == 45) {
                    arg0.consume();
                }
                System.out.println(arg0.getKeyCode());
            }

            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyTyped(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }
        });

        contentPane = new JPanel(new BorderLayout());
        contentPane.add(usernameField);

        return contentPane;
    }

}


推荐答案

使用 DocumentFilter

NumberOnlyFilter.java:

import javax.swing.*;
import javax.swing.text.*;
import java.util.regex.*;
public class NumberOnlyFilter extends DocumentFilter
{

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.insertString(offset, text, attr);
    }
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(offset, offset + length, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.replace(offset, length, text, attr);
    }

    /**
     * This method checks if a String contains only numbers
     */
    public boolean containsOnlyNumbers(String text)
    {
        Pattern pattern = Pattern.compile("([+-]{0,1})?[\\d]*");
        Matcher matcher = pattern.matcher(text);
        boolean isMatch = matcher.matches();
        return isMatch;
    }

}

然后你就可以像使用它一样:

and then you can use it like:

((AbstractDocument)yourTxtField.getDocument()).setDocumentFilter(new NumberOnlyFilter());

这篇关于只允许将数字和符号( - )输入JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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