In a Chatroom code, I have been trying to figure out how to add a code so I can reject client with a username that already exists. I have created an ArrayList
where I can store the usernames of the connected clients. But every time I run a client, it accepts a name that I have previously used. This is my code.
if(obj == login) {
// Need to establish a connection request
String username = tf.getText().trim();
clientList.add(username);
// ignore empty username
if(username.length() == 0 || username.equals("Your name")){
JOptionPane.showMessageDialog(null,"Please enter a valid username","Alert Message",JOptionPane.WARNING_MESSAGE);
return;
}
if(clientList.size() > 1 && clientList.contains(username)){
JOptionPane.showMessageDialog(null,"This username is in use","Alert Message",JOptionPane.WARNING_MESSAGE);
return;
}
// try creating a new Client with GUI
client = new Client(username, this);
// test if we can start the Client
if(!client.start())
return;
//clientList.add(client);
tf.setText("");
tf.setBackground(Color.YELLOW);
label.setText("Enter your message in the yellow box");
connected = true;
login.setEnabled(false);
logout.setEnabled(true);
tf.addActionListener(this);
// Action listener for when the user enter a message
}
Any help please?
As the comment of @Elliott-Frisch, You need to add username
to clientList after you check its validity. You may also simplify clientList.size() > 1 && clientList.contains(username))
as clientList.contains(username)
You can just put clientList.add(username);
before the line you create the client object:
clientList.add(username);
//try creating a new Client with GUI
client = new Client(username, this);
//test if we can start the Client