import javax.swing.*; import java.awt.*; import java.awt.BorderLayout; import java.awt.event.*; public class ChatClient extends JPanel { private JFrame frame; private JTextArea textArea; private JTextField textField; private JButton sendButton; private JButton quitButton; public ChatClient() { frame = new JFrame("Chat Client"); textArea = new JTextArea(10, 50); textField = new JTextField(50); sendButton = new JButton("send"); quitButton = new JButton("quit"); } public void launchFrame() { JPanel mainPanel = new JPanel(new BorderLayout()); JPanel buttonPanel = new JPanel(new GridLayout(2, 1)); JPanel sendPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JPanel quitPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); sendPanel.add(sendButton); quitPanel.add(quitButton); buttonPanel.add(sendPanel); buttonPanel.add(quitPanel); mainPanel.add(textArea, BorderLayout.CENTER); mainPanel.add(textField, BorderLayout.SOUTH); mainPanel.add(buttonPanel, BorderLayout.EAST); frame.getContentPane().add(mainPanel); // Add listeners sendButton.addActionListener(new SendButtonListener()); quitButton.addActionListener(new QuitButtonListener()); frame.addWindowListener(new CloseWindowListener()); textField.addActionListener(new EnterKeyListener()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { ChatClient chatClient = new ChatClient(); chatClient.launchFrame(); } class SendButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { textArea.append(textField.getText() + "\n"); textField.setText(""); } } class QuitButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } class CloseWindowListener extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } class EnterKeyListener implements ActionListener { public void actionPerformed(ActionEvent e) { textArea.append(textField.getText() + "\n"); textField.setText(""); } }
时间: 2024-04-26 13:21:39 浏览: 173
import java.awt.docx
这段代码实现了一个简单的聊天客户端界面。界面中包括一个文本区域用于显示聊天内容,一个文本框用于输入聊天信息,一个发送按钮和一个退出按钮。用户输入聊天信息后,可以通过点击发送按钮或者按下回车键来发送信息,发送后文本框会清空。点击退出按钮或者关闭窗口可以退出客户端。这个聊天客户端的界面并没有实现网络通信功能,需要通过其他方式来实现与聊天服务器的通信。
阅读全文