用java的swing写一个聊天界面,用代码实现
时间: 2024-06-10 16:09:21 浏览: 13
好的,以下是一个简单的Java Swing聊天界面的实现代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChatUI extends JFrame {
private JTextArea chatArea;
private JTextField inputField;
private JButton sendButton;
public ChatUI() {
initComponents();
}
private void initComponents() {
chatArea = new JTextArea();
chatArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatArea);
inputField = new JTextField();
inputField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendButton.doClick();
}
});
sendButton = new JButton("发送");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
if (!text.isEmpty()) {
chatArea.append(text + "\n");
inputField.setText("");
}
}
});
JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel.add(inputField, BorderLayout.CENTER);
inputPanel.add(sendButton, BorderLayout.EAST);
this.setTitle("聊天界面");
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.add(scrollPane, BorderLayout.CENTER);
this.add(inputPanel, BorderLayout.SOUTH);
this.setSize(400, 300);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChatUI().setVisible(true);
}
});
}
}
```
这段代码实现了一个简单的聊天界面,包括一个文本框用于输入聊天内容,一个发送按钮用于发送聊天内容,以及一个文本区域用于显示聊天记录。用户在文本框中输入内容后,可以按回车键或点击发送按钮发送聊天内容,发送后聊天内容会显示在文本区域中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)