package com.test.view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class ChatJFrame extends JFrame implements ActionListener
{
private JTextArea text_receiver; // 显示对话内容的文本区
private JTextField text_sender; // 输入发送内容的文本行
private PrintWriter cout; // 字符输出流对象
private String name; // 网名
public ChatJFrame(String name, String title, PrintWriter cout) // 构造方法
{
super("聊天室 " + name + " " + title);
this.setSize(320, 240);
this.setLocation(300, 240);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.text_receiver = new JTextArea();
this.text_receiver.setEditable(false); // 不可编辑
this.add(this.text_receiver);
JPanel panel = new JPanel();
this.add(panel, "South");
this.text_sender = new JTextField(12);
panel.add(this.text_sender);
this.text_sender.addActionListener(this); // 注册单击事件监听器
JButton button_send = new JButton("发送");
panel.add(button_send);
button_send.addActionListener(this);
JButton button_leave = new JButton("离线");
panel.add(button_leave);
button_leave.addActionListener(this);
this.setVisible(true);
this.setWriter(cout);
this.name = name;
}
public ChatJFrame()
{
this("", "", null);
}
public void setWriter(PrintWriter cout) // 设置字符输出流对象
{
this.cout = cout;
}
public void receive(String message) // 显示对方发来的内容
{
text_receiver.append(message + "\r\n");
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "离线")
{
if (this.cout != null)
{
this.cout.println(name + "离线");
this.cout.println("bye");
this.cout = null;
}
text_receiver.append("我离线\n");
} else // 发送
{
if (this.cout != null)
{
this.cout.println(name + " 说:" + text_sender.getText());
text_receiver.append("我说:" + text_sender.getText() + "\n");
text_sender.setText("");
} else
text_receiver.append("已离线,不能再发送。\n");
}
}
public static void main(String args[])
{
new ChatJFrame();
}
}
阅读(954) | 评论(0) | 转发(0) |