java jTextField 只接受字母和空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14058505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:55:22  来源:igfitidea点击:

jTextField accept only alphabet and white space

javaswingfilterjtextfield

提问by mxyz

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

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

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

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

now i changed the code

现在我改变了代码

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

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

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

回答by David Kroukamp

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

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

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

    }
}

回答by Lee Meador

You have a semicolon on the end of the first line. So it is not really testing correctly.

第一行的末尾有一个分号。所以它并没有真正正确地测试。

A statement like this (which is what you have):

像这样的声明(这就是你所拥有的):

if (condition) ;

will execute the empty statement (;) if the condition is true and then go to the next line. If the condition is false, it will just go to the next line. These two actions have the same result.

如果条件为真,将执行空语句 (;) 然后转到下一行。如果条件为假,它只会转到下一行。这两个操作具有相同的结果。

You might try using braces on all "if" statements. It is tedious at times but makes it harder to mess up.

您可以尝试在所有“if”语句上使用大括号。有时很乏味,但更难搞砸。

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

That's what I would do. You can just erase the semicolon.

这就是我会做的。您可以删除分号。

回答by Atharva_I

This code might help you :

此代码可能对您有所帮助:

answerField1.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            char ch = e.getKeyChar();
            if(Character.isDigit(ch)){
                answerField1.setText("");
                JOptionPane.showMessageDialog(null, "Enter Alphabet Only !");
                                     }
                                            }
    });