jTextField 只接受字母和空格 [英] jTextField accept only alphabet and white space

查看:16
本文介绍了jTextField 只接受字母和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户只输入字母或空格如果用户输入其他字符,我想用 jOptionPane 给消息我已经搜索过并尝试了以下代码

i want user to enter only alphabet or white space if user enters other character , i want give message with jOptionPane i have searched and i tried the below code

if (!(Pattern.matches("^[a-zA-Z]+$", answerField1.getText())))
        JOptionPane.showMessageDialog(null, "Please enter a valid character", "Error", JOptionPane.ERROR_MESSAGE);

但现在无论我输入什么都会出错

but now whatever i enter it gives the error

现在我改变了代码

Pattern letterPattern = Pattern.compile("^[a-zA-Z]+$");

if (!(letterPattern.matcher(answerField1.getText()).matches()))
      {
    JOptionPane.showMessageDialog(null, "Please enter a valid character", "Error", JOptionPane.ERROR_MESSAGE);
}

现在它只在用户输入 number 时才给出消息.我该如何解决这个问题

now it gives message only firs time user enters number . how can i solve this

推荐答案

使用DocumentFilter,这里是我做的一个例子,它只接受字母字符和空格:

Use a DocumentFilter, here is an example I made, it will only accept alphabetic characters and white spaces:

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;
import javax.swing.text.DocumentFilter.FilterBypass;

public class Test {

    public Test() {
        initComponents();
    }

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

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField jtf = new JTextField();
        //add filter to document
        ((AbstractDocument) jtf.getDocument()).setDocumentFilter(new MyDocumentFilter());

        frame.add(jtf);

        frame.pack();
        frame.setVisible(true);
    }
}

class MyDocumentFilter extends DocumentFilter {

    @Override
    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
        for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
            char c = string.charAt(n - 1);//get a single character of the string
            System.out.println(c);
            if (Character.isAlphabetic(c) || c == ' ') {//if its an alphabetic character or white space
                super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character
            } else {//it was not an alphabetic character or white space
                System.out.println("Not allowed");
            }
        }
    }

    @Override
    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
        super.remove(fb, i, i1);
    }

    @Override
    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
        super.insertString(fb, i, string, as);

    }
}

这篇关于jTextField 只接受字母和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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