请用java编写完成如下图形用户界面: 聊天窗口 本人 你好 聊天信息不能为空 聊天信息不能为空 本人再见 聊天信息 发送
时间: 2024-11-15 14:23:06 浏览: 6
在Java中,我们可以使用Swing库来创建简单的图形用户界面(GUI),模拟一个基本的聊天室应用。以下是一个简单的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChatWindow extends JFrame {
private JTextArea chatHistory;
private JTextField userInput;
private JButton sendButton;
public ChatWindow() {
setTitle("简单聊天窗口");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建聊天历史区域
chatHistory = new JTextArea();
chatHistory.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatHistory);
add(scrollPane, BorderLayout.NORTH);
// 创建输入框和发送按钮
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
userInput = new JTextField(20);
userInput.setRequired(true); // 设置输入框不可为空
sendButton = new JButton("发送");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = userInput.getText();
if (!inputText.isEmpty()) { // 检查是否为空
chatHistory.append("\n本人: " + inputText); // 添加到聊天历史
userInput.setText(""); // 清空输入框
} else {
JOptionPane.showMessageDialog(null, "聊天信息不能为空", "错误提示", JOptionPane.ERROR_MESSAGE);
}
}
});
panel.add(userInput);
panel.add(sendButton);
add(panel, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ChatWindow();
});
}
}
```
在这个例子中,我们创建了一个JFrame窗口,包含一个滚动的聊天历史文本区、一个输入框和一个发送按钮。当点击发送按钮时,如果输入框内容非空,则将文本添加到聊天历史并清空输入框;若输入框为空,则弹出错误消息。
阅读全文