创建群聊详细过程以及思路
思路简述
首先看到我们的创建群聊页面
可以看到咱们左边是checkbox(显示的是该用户的所有好友)
右边是vbox,显示的是已经选中的群聊初始成员(点击checkbox就跳到右边框框里)
右下的textFiled填的是群聊名称
点击确定创建群聊,进行数据库操作,写在"确定"按钮的on action里
面临的问题
怎么获取右边vbox的好友id呢?
因为我右边的控件是AnchorPane,里面包含一些小组件,单独在“确定”按钮的on action里不方便一个一个得获取,所以我这边呢想到可以定义一个全局的字符串数组Members【】,然后再checkbox的操作里写,如果勾选了,就将这个用户账号存到Members里,如果取消勾选,就将取消的用户账号从Members里删掉,怎么删呢
这样,删除一个数组中index位置(自个写循环来得到它的值)的元素,使用System.arraycopy()对原数组进行复制操作,将原来的数组长度减一,再进行差位复制,最后返回更新了的这个数组。
//删除字符串数组中的特定元素
public String[] delElement(String[] arrays, String faccount) {
int index = 0;
for(int i=0;i<arrays.length;i++){
if(faccount.equals(arrays[i])){
//该好友在的位置
index = i;
}
}
//判断数据合理性
if (index >= 0 && index < arrays.length) {
String[] arrays_result = new String[arrays.length - 1];
//将arrays数组在index前的元素都复制到新数组arrays_result中
System.arraycopy(arrays, 0, arrays_result, 0, index);
//判断index之后是否还有元素,有则将index后的元素从index位置复制到新数组中
if (index < arrays.length - 1) {
System.arraycopy(arrays, index + 1, arrays_result, index, arrays_result.length - index);
}
return arrays_result;
}
return null;
}
checkbox的操作这样写,nums【0】表示Members存的好友账号的个数(全局变量)
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//勾选目标好友控件
if(newValue){
//将该好友弄到右边(已选择的群聊成员)
members.getChildren().add(ap);
nums[0]++;
//显示的已经选择到的群聊人数++
num.setText("已选联系人:("+ nums[0] +")");
//将该好友的账号存到这个字符串数组
Members[nums[0]] = imp.getinfo2(id).getAcountnum();
}else{
//将目标好友从右边移除
members.getChildren().remove(ap);
nums[0]--;
//显示的已经选择到的群聊人数--
num.setText("已选联系人:("+ nums[0] +")");
//将该好友账号从字符串数组中删掉
Members = delElement(Members, imp.getinfo2(id).getAcountnum());
}
}
});
最后就是顺利得在“确定”按钮的on action里将数据都存到数据库啦,再将这个群聊都显现到用户的聊天列表里,然后在server里写群聊。信息就都发给群成员就是了。