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