0

在聊天室代码中,我一直在尝试弄清楚如何添加代码,以便可以拒绝具有已存在用户名的客户。我创建了一个ArrayList可以存储已连接客户端的用户名的位置。但是每次我运行客户端时,它都会接受我以前使用过的名称。这是我的代码。

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
}

请问有什么帮助吗?

4

2 回答 2

0
if (!clientList.contains(username)){

  clientList.add(username);

}
于 2013-12-23T16:10:19.400 回答
0

正如@Elliott-Frisch 的评论,您需要username在检查其有效性后添加到 clientList。您也可以简化clientList.size() > 1 && clientList.contains(username))clientList.contains(username)

您可以clientList.add(username);在创建客户端对象的行之前放置:

clientList.add(username);
//try creating a new Client with GUI
client = new Client(username, this);
//test if we can start the Client
于 2013-12-23T16:12:59.193 回答