如何在Java中验证文本框字段中的用户名?

huangapple go评论84阅读模式
英文:

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

问题

以下是您提供的代码的翻译部分:

所以我想要在游戏继续之前验证用户输入的用户名长度应在6到30个字符之间不允许使用数字),我在互联网上搜索并了解了正则表达式我不太熟悉它所以遇到了一些问题以下是代码应该执行的操作如果用户没有输入用户名或者在单击开始游戏按钮时输入的用户名包含不允许的字符我希望弹出一个对话框告诉他重新尝试如果一切都正确游戏应该正常进行但是当我运行此代码时用户名没有被检查而是进入游戏而不管在文本框中输入了什么下面是我目前为止的代码

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;

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

    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);
    }
}
英文:

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

}

答案1

得分: 0

我尝试将您的 isValidUsername 作为独立方法使用,但它没有给出有效的结果。 即使对于有效的名称,它也返回 false。 我将其更改为以下内容,它运行良好:

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

此外,由于代码在单击 btnStartGame 按钮后执行,因此按钮处于禁用状态是不可能的(禁用的按钮不会触发事件)。 出于这个原因,我认为检查 if(btnStartGame.isEnabled()) 是多余的(我可能错了)。 因此,您可以只检查:

if (isValidUsername(field)) {
  //在此开始游戏
} else {
  //在此显示提示
}
英文:

I tried your isValidUsername as a standalone method and it didn't give valid results. 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). For that reason, I think the check if(btnStartGame.isEnabled()) is redundant (I may be wrong). You can hence just check:

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

答案2

得分: 0

以下是您问题中代码的翻译部分:

这两行来自您在问题中发布的代码:

String field;
field = textbox_name.getText();

需要放在actionPerformed()方法内部,因为您希望在用户单击btnStartGame按钮之后获取textbox_name的内容。

这是我对您发布的代码的重新编写:

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

顺便提一下,您应该尝试使用布局管理器

英文:

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.

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.

huangapple
  • 本文由 发表于 2020年8月4日 01:59:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定