如何确保JTextField只包含字母?

时间:2021-10-14 06:42:23

I want to take only letters as a input in my name field.

我想在我的名字字段中仅将字母作为输入。

I have already tried using the matches method but unfortunately something is wrong and the exception is being thrown.

我已经尝试过使用匹配方法,但遗憾的是出现了错误,并且抛出了异常。

Is there any other method of checking the same?

还有其他检查方法吗?

   import java.awt.BorderLayout;
   import java.awt.FlowLayout;
   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.GridLayout;
   import java.awt.Insets;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import javax.swing.*;


    public class CreateAccount extends JFrame implements ActionListener{

    JPanel details = new JPanel(new GridBagLayout());

    JLabel fName= new JLabel("First Name:");
    JTextField firstNameField = new JTextField(10);

    JLabel lName= new JLabel("Last Name:");
    JTextField lastNameField = new JTextField(10);

    JLabel initialDeposit = new JLabel("Initial Deposit: ");
    JTextField initialDepositField = new JTextField(10);

    String accountTypes[] = {"Savings","Current"};

    JComboBox accountTypesComboBox = new JComboBox(accountTypes);
    JLabel accountType= new JLabel("Account type: ");

    JButton submit = new JButton("SUBMIT");
    JButton review = new JButton("REVIEW");

    Administrator admin = new Administrator();
    User u[] = new User[admin.maxNumberOfUsers];

    CreateAccount() {
        buildGui();
        setSize(400,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void initialiseUserCount() {
        admin.numberOfSavingsAccount = 0;
        admin.numberOfCurrentAccount = 0;
        admin.numberOfUsers=0;
    }
    public void buildGui() {

        setTitle("New Account Form");

        //JPanel submitPanel = new JPanel();
        //submitPanel.add(submit);


        GridBagConstraints c = new GridBagConstraints();
        c.insets=new Insets(10,10,10,10);
        // Stretch components horizontally (but not vertically) 
        c.fill = GridBagConstraints.HORIZONTAL;
        // Components that are too short or narrow for their space
        // Should be pinned to the northwest (upper left) corner
        c.anchor = GridBagConstraints.NORTHWEST;
        // Give the "last" component as much space as possible
        c.weightx = 1.0;

        c.gridx=0;
        c.gridy=0;
        details.add(fName,c);
        c.gridx=1;
        c.gridy=0;
        details.add(firstNameField,c);
        c.gridx=0;
        c.gridy=1;
        details.add(lName,c);
        c.gridx=1;
        c.gridy=1;
        details.add(lastNameField,c);
        c.gridx=0;
        c.gridy=2;
        details.add(initialDeposit,c);
        c.gridx=1;
        c.gridy=2;
        details.add(initialDepositField,c);
        c.gridx=0;
        c.gridy=3;
        details.add(accountType,c);
        c.gridx=1;
        c.gridy=3;
        details.add(accountTypesComboBox,c);
        c.gridx=0;
        c.gridy=4;
        details.add(submit,c);
        c.gridx=1;
        c.gridy=4;
        details.add(review,c);
        add(details);

        firstNameField.addActionListener(this);
        review.addActionListener(this);

    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==firstNameField) {
            try {
                String uFName = firstNameField.getText().toString();

                if(!uFName.matches("[A-Za-z]+"))
                    throw new Exception();
            }
            catch(Exception e1) {
                firstNameField.setText("");
                JOptionPane.showMessageDialog(firstNameField,"Please enter a valid name!");
            }
        }
    }
}

2 个解决方案

#1


2  

You can try to use this regex

您可以尝试使用此正则表达式

if(!uFName.matches("^[a-zA-Z]+$"))

#2


3  

Use a DocumentFilter. It will allow you to perform real time validation of the text fields

使用DocumentFilter。它将允许您执行文本字段的实时验证

See Implementing a Document Filter and DocumentFilter Examples for more details

有关更多详细信息,请参阅实现文档筛选器和DocumentFilter示例

For example...

public class CharFilter extends DocumentFilter {

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

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

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

And applied using something like...

并使用像...这样的东西

JTextField firstNameField = new JTextField(20);
((AbstractDocument)firstNameField.getDocument()).setDocumentFilter(new CharFilter());

#1


2  

You can try to use this regex

您可以尝试使用此正则表达式

if(!uFName.matches("^[a-zA-Z]+$"))

#2


3  

Use a DocumentFilter. It will allow you to perform real time validation of the text fields

使用DocumentFilter。它将允许您执行文本字段的实时验证

See Implementing a Document Filter and DocumentFilter Examples for more details

有关更多详细信息,请参阅实现文档筛选器和DocumentFilter示例

For example...

public class CharFilter extends DocumentFilter {

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

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

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

And applied using something like...

并使用像...这样的东西

JTextField firstNameField = new JTextField(20);
((AbstractDocument)firstNameField.getDocument()).setDocumentFilter(new CharFilter());