I'm making a simple chat through Swing, and having some issues.
I'm trying to make my client send a private message to another user when it get's input "/w anotheruserid". It's not about the EventHandler, but how to recognize the string. The event handler is to be like the one below.
public void keyTyped(KeyEvent e) {
if(textField.getText().equals("/w ")){
}
}
How should I make it to get additional string input such as another user's id?
use startsWith
if(textField.getText().startsWith("/w ")){
}
That way you can simply substring the text and exclude the /w
part to use it as /w something
.
String message = textField.getText().substring(2);
您可以为此使用正则表达式,或者可以使用String子字符串函数来获取前两个字符,然后可以将它与“/ w”匹配。
if(textField.getText().equals("/w ")){
This condition is true only if the text in textField is " /w
";
You can use if(textField.getText().startsWith("/w "))
instead.
And then you can remove the first 3 characters, including '/', 'w' and Space ' ', to populate another user id.
Using StringValue.substring(3)
;
An example is as follows:
String text = "/w anotheruserid";
System.out.printf("Before populating anotheruserid==>%s\n", text);
if (text.startsWith("/w ")) {
text = text.substring(3);
/*
* Remove the first 3 characters, including '/' ,'w' and ' ')
*/
System.out.printf("After Populating anotheruserid==>%s\n", text);
}
Output in Console:
Before populating anotheruserid==>/w anotheruserid
After Populating anotheruserid==>anotheruserid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.