获取代码以拒绝用户名(如果它存在于ArrayList中)。

时间:2013-12-23 16:07:39

标签: java client chatroom

在聊天室代码中,我一直试图找出如何添加代码,以便我可以使用已存在的用户名来拒绝客户端。我创建了一个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
}

请帮忙吗?

2 个答案:

答案 0 :(得分:0)

if (!clientList.contains(username)){

  clientList.add(username);

}

答案 1 :(得分: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