jtextfield的字母表验证

时间:2014-10-28 05:11:56

标签: java swing

我一直试图在jtextfield中显示字母。即使按下其他键,jtextfield也不应显示它们只显示字母表。请你帮我这个..

2 个答案:

答案 0 :(得分:1)

首先看一下Implementing a Document Filter

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestFilter {

    public static void main(String[] args) {
        new TestFilter();
    }

    public TestFilter() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTextField field = new JTextField(10);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new CharFilter());

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class CharFilter extends DocumentFilter {

        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset,
                        String string, AttributeSet attr)
                        throws BadLocationException {

            StringBuilder buffer = new StringBuilder(string);
            for (int i = buffer.length() - 1; i >= 0; i--) {
                char ch = buffer.charAt(i);
                if (!Character.isAlphabetic(ch)) {
                    buffer.deleteCharAt(i);
                }
            }
            super.insertString(fb, offset, buffer.toString(), attr);
        }

        @Override
        public void replace(DocumentFilter.FilterBypass fb,
                        int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            if (length > 0) {
                fb.remove(offset, length);
            }
            insertString(fb, offset, string, attr);
        }
    }
}

您也可以找到DocumentFilter Examples有用的

答案 1 :(得分:-1)

这里有一个解决方案,如果你只想输入字母到jtextfield,并且即使它们被按下也不应该输入其他键。在你的jframe中只需选择你的jtextfield右键单击jtextfield就可以找到事件然后转到events点击keyTyped事件,然后编写以下代码,只输入字母到你的jtextfield。

private void tfempidKeyTyped(java.awt.event.KeyEvent evt){
        // TODO在这里添加您的处理代码:

    char key = evt.getKeyChar();
    if (key > '0' && key < '9') {
        evt.consume();
    }