import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.bind.JAXB;
public class ClientChat extends JFrame {
private String userName;//登陆成功的用户名
private JTextArea jta_recive=new JTextArea(15,25);//显示接受到消息的组件
private JComboBox jcb_users=new JComboBox();//在线用户的下接框
private File myfile;
public static void main(String [] args){
new ClientChat("林海方");//生成一个对象
}
public ClientChat(String userName){
this.userName=userName;//用户名
add(jta_recive);
add(jcb_users);
showFrame();
initial();
}
public void showFrame(){
this.setTitle("netjava 欢迎"+this.userName+"的使用!!!");
java.awt.FlowLayout f1=new java.awt.FlowLayout(0);
this.setLayout(f1);
this.setSize(300, 500);
this.setDefaultCloseOperation(3);
this.setVisible(true);
}
private void initial(){
JLabel la_name = new JLabel("接收到的消息");
JLabel la_users = new JLabel("发送给:");
final JTextField jtf_send = new JTextField(25);//发送输出框
javax.swing.JButton bu_send = new javax.swing.JButton("send");
javax.swing.JButton bu_history = new javax.swing.JButton("聊天记录");
jcb_users.addItem("张三");
jcb_users.addItem("李四");
jcb_users.addItem("王保长");
add(la_name);
add(jta_recive);
add(jcb_users);
add(jtf_send);
add(la_users);
add(jcb_users);
add(bu_send);
add(bu_history);
ActionListener sendListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
byte[] chi;
String reciver = (String) jcb_users.getSelectedItem();
reciver = reciver.trim();//去除空格
String content = jtf_send.getText();//
jta_recive.append(userName+"对"+reciver+"说:"+content+"\r\n");//显示到桌面
jtf_send.setText("");
myfile = new File ("G:\\Java实验7.txt");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(myfile,true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
chi=content.getBytes();
try {
fout.write(chi);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
ActionListener historyListener = new ActionListener(){ /**/
// String content_history;
public void actionPerformed(ActionEvent e){
byte [] b = new byte[1024];
FileInputStream fin = null;
try {
fin = new FileInputStream(myfile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = "sefsdfg";
try {
fin.read(b);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
message =new String(b);
jta_recive.append("聊天记录:"+message);
}
};
bu_send.addActionListener(sendListener);
jtf_send.addActionListener(sendListener);
bu_history.addActionListener(historyListener);
jtf_send.setText("");
}
}
追问要求:
使用图形用户界面。
能实现一个聊天室中多人聊天。
可以两人私聊。
提示:使用socket通信