JAVA聊天室中把非好友的用户放进陌生人面板中的具体代码
时间: 2024-02-12 19:02:27 浏览: 155
在Java聊天室中把非好友的用户放进陌生人面板中,可以使用Java Swing中的JList控件实现。具体实现方式如下:
```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChatRoom extends JFrame {
private JList<String> friendList;
private JList<String> strangerList;
public ChatRoom() {
// 初始化组件等代码
// ...
// 添加好友按钮的点击事件监听器
addFriendBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取好友列表中选中的好友
String friend = friendList.getSelectedValue();
if (friend != null) {
// 把好友添加到聊天室中
// ...
} else {
JOptionPane.showMessageDialog(ChatRoom.this, "请选择一个好友");
}
}
});
// 添加陌生人按钮的点击事件监听器
addStrangerBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取陌生人列表中选中的陌生人
String stranger = strangerList.getSelectedValue();
if (stranger != null) {
// 把陌生人添加到陌生人面板中
DefaultListModel<String> model = (DefaultListModel<String>) strangerList.getModel();
model.removeElement(stranger);
DefaultListModel<String> strangerModel = (DefaultListModel<String>) strangerPanel.getModel();
strangerModel.addElement(stranger);
} else {
JOptionPane.showMessageDialog(ChatRoom.this, "请选择一个陌生人");
}
}
});
}
}
```
在陌生人面板中使用JList控件,需要在构造函数中创建一个DefaultListModel对象,并把它设置为JList控件的数据模型。当需要把陌生人添加到陌生人面板中时,首先获取陌生人列表中选中的陌生人,然后从陌生人列表的数据模型中删除该陌生人,并把它添加到陌生人面板的数据模型中。这样就可以实现把非好友的用户放进陌生人面板中的功能了。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)