简体   繁体   English

如何在 Java 的教科书字段中验证用户名?

[英]How can I validate the username in a textbook field in Java?

So I wanted to validate the username (length should be between 6 to 30 characters, and numbers should not be allowed) that the user entered before the game proceeds, and I searched the internet and found out about the regex expressions.所以我想验证用户在游戏继续之前输入的用户名(长度应该在 6 到 30 个字符之间,并且不应该允许数字),我搜索了互联网并找到了正则表达式。 I am not used to it so I have found some problems.我不习惯,所以我发现了一些问题。 The code should do the following: if the user didn't enter a username or if it contained characters not allowed when he clicked the "start game" button, I wanted a dialog box to pop up and tell him to try again.代码应该执行以下操作:如果用户没有输入用户名,或者当他单击“开始游戏”按钮时包含不允许的字符,我希望弹出一个对话框并告诉他再试一次。 And if everything was correct the game should proceed as normal, but when I run this code the username is not checked and it enters the game despite what is entered in the text box, and below is what I have so far.如果一切正常,游戏应该会正常进行,但是当我运行此代码时,不会检查用户名,尽管在文本框中输入了内容,但它会进入游戏,以下是我目前所拥有的。

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import java.util.regex.*;

public class StartScreen extends JFrame {

private JPanel contentPane;
private JTextField textbox_name;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                StartScreen frame = new StartScreen();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */

public static boolean isValidUsername(String name) 
{ 
    String regex = "^[a-zA-Z]{5,29}$";  //Removed ^[aA-zZ]\\\\w{5,29}$
    Pattern p = Pattern.compile(regex);     
    if (name == null) { 
        return false; 
    }   
    Matcher m = p.matcher(name);    
    return m.matches(); 
 } 

public StartScreen() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 455, 191);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    
    JLabel lblEnterName = new JLabel("Enter Name:");
    lblEnterName.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
    lblEnterName.setBounds(91, 48, 102, 29);
    contentPane.add(lblEnterName);
    
    textbox_name = new JTextField();
    textbox_name.setBounds(205, 49, 130, 28);
    contentPane.add(textbox_name);
    textbox_name.setColumns(10);
    
    String field;
    field = textbox_name.getText();
    
    JButton btnStartGame = new JButton("Start Game");
    btnStartGame.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            
            if(isValidUsername(field)) {
                MainScreen window = new MainScreen();
                window.setVisible(true);
                dispose();
            }
            else {
                JOptionPane.showMessageDialog(null, "Please enter your username correctly");
            }
        }
    });
    
    
    
    btnStartGame.setBounds(150, 102, 117, 29);
    contentPane.add(btnStartGame);
}

} }

I tried your isValidUsername as a standalone method and it didn't give valid results.我尝试将您的isValidUsername作为独立方法,但没有给出有效结果。 It was giving false even for valid names.即使对于有效名称,它也是错误的。 I changed it to the following and it worked well:我将其更改为以下内容并且效果很好:

public static boolean isValidUsername(String name) 
{ 
    String regex = "^[a-zA-Z]{5,29}$";  //Removed ^[aA-zZ]\\\\w{5,29}$
    Pattern p = Pattern.compile(regex);     
    if (name == null) { 
        return false; 
    }   
    Matcher m = p.matcher(name);    
    return m.matches(); 
 } 

Also, since the code is being executed after the button btnStartGame has been clicked, its not therefore possible that the button is disabled (A disabled button doesn't fire events).此外,由于在单击按钮 btnStartGame 之后执行代码,因此按钮不可能被禁用(禁用的按钮不会触发事件)。 For that reason, I think the check if(btnStartGame.isEnabled()) is redundant (I may be wrong).出于这个原因,我认为检查if(btnStartGame.isEnabled())是多余的(我可能错了)。 You can hence just check:因此,您可以检查:

if(sValidUsername(field)){
  //start game here
} else {
  //display prompt here
}

These two lines from the code you posted in your question:您在问题中发布的代码中的这两行:

String field;
field = textbox_name.getText();

need to be inside method actionPerformed() because you want to get the contents of textbox_name after the user clicks on the button btnStartGame .需要方法actionPerformed()中,因为您想在用户单击按钮textbox_name获取btnStartGame的内容。

Here is my rewrite of the code you posted.这是我对您发布的代码的重写。

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import java.util.regex.*;

public class StartScreen extends JFrame {

private JPanel contentPane;
private JTextField textbox_name;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                StartScreen frame = new StartScreen();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */

public static boolean isValidUsername(String name) 
{ 
    String regex = "^[a-zA-Z]{5,29}$";  //Removed ^[aA-zZ]\\\\w{5,29}$
    Pattern p = Pattern.compile(regex);     
    if (name == null) { 
        return false; 
    }   
    Matcher m = p.matcher(name);    
    return m.matches(); 
 } 

public StartScreen() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 455, 191);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    
    JLabel lblEnterName = new JLabel("Enter Name:");
    lblEnterName.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
    lblEnterName.setBounds(91, 48, 102, 29);
    contentPane.add(lblEnterName);
    
    textbox_name = new JTextField();
    textbox_name.setBounds(205, 49, 130, 28);
    contentPane.add(textbox_name);
    textbox_name.setColumns(10);
    
    JButton btnStartGame = new JButton("Start Game");
    btnStartGame.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String field;  // added this line
            field = textbox_name.getText();  // added this line
            
            if(isValidUsername(field)) {
                MainScreen window = new MainScreen();
                window.setVisible(true);
                dispose();
            }
            else {
                JOptionPane.showMessageDialog(null, "Please enter your username correctly");
            }
        }
    });
    
    btnStartGame.setBounds(150, 102, 117, 29);
    contentPane.add(btnStartGame);
}

By the way, you should try to use layout managers .顺便说一句,您应该尝试使用布局管理器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM