package com.hyn;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;public class Talklogin extends JFrame{
/**
 * 
 */
private static final long serialVersionUID = 1L;
private ObjectOutputStream oos;
private JList user_list;
private JTextArea show_jta;
private JTextField send_jtf;
private JTextField jtf_username;
 private boolean loginFlag = false;
public void  createsocketlogin(){
try {
Socket socket=new Socket("localhost", 8765);
oos=new ObjectOutputStream(socket.getOutputStream());
new loginthread(socket).start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

class loginthread extends Thread{
Socket socket;
public loginthread(Socket socket){
this.socket=socket;
}

public void run(){
try {
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
DefaultListModel dcbm=(DefaultListModel)user_list.getModel();
while(true){
String getout=br.readLine().trim();
if(!getout.startsWith("MEG:")){
if(getout.startsWith("退出:")){
dcbm.removeElement(getout.substring(3));
}else{
@SuppressWarnings("unused")
boolean flag=false;
for(int i=0;i<dcbm.getSize();i++){
if(getout.equals((String) dcbm.getElementAt(i))){
flag=true;
break;
}
}
if(flag=false){
dcbm.addElement(getout);
}
}
}else{
DateFormat df=DateFormat.getDateInstance();
String date=df.format(new Date());
df = DateFormat.getTimeInstance(DateFormat.MEDIUM);
                        String time = df.format(new Date()); 
                        String senduser=getout.substring(4, getout.indexOf(":发送给:"));
                        String receive=getout.substring(getout.indexOf(":的消息是:")+6);
                        show_jta.append(" "+senduser+" "+date+" "+time+"\n  "+receive+"\n");
                        show_jta.setSelectionStart(show_jta.getText().length()-1);
                        show_jta.setSelectionEnd(show_jta.getText().length());
                        send_jtf.requestFocus();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

public void send(){
String loginusername=jtf_username.getText().trim();
String getout=send_jtf.getText();
if(getout.equals("")){
return;
}
ArrayList<String> al=new ArrayList<String>();
Object[] receiveusername=user_list.getSelectedValues();
if(receiveusername.length<=0){
return;
}
for(int i=0;i<receiveusername.length;i++){
String message=loginusername+":发送给:"+(String)receiveusername[i]+":的消息是:"+getout;
al.add(message);
}
try {
oos.writeObject(al);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
DateFormat df=DateFormat.getDateInstance();
String date=df.format(new Date());
df = DateFormat.getTimeInstance(DateFormat.MEDIUM);
        String time = df.format(new Date()); 
        String senduser=jtf_username.getText().trim();
        String receiveout=send_jtf.getText().trim();
        show_jta.append("   "+senduser+"   "+date+"   "+time+"\n  "+receiveout+"\n");
        send_jtf.setText(null);
        show_jta.setSelectionStart(show_jta.getText().length()-1);
        show_jta.setSelectionEnd(show_jta.getText().length());
        send_jtf.requestFocus();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Talklogin tl=new Talklogin();
tl.createsocketlogin();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
} public Talklogin(){
super();
try {
setIconImage(ImageIO.read(Thread.currentThread().getContextClassLoader().getResource("logo.jpg")));
} catch (IOException e) {
e.printStackTrace();
}
setTitle("聊天室登录");
setSize(360, 200);
setLocation(500, 250);
JPanel jp=new JPanel();
jp.setLayout(null);
add(jp);

ImageIcon icon = new ImageIcon("image/1.png");
JLabel jl = new JLabel(icon);
jl.setBounds(0, 0, 340, 70);
jp.add(jl);

JLabel jla=new JLabel("用户名:");
jla.setBounds(0, 80, 60, 40);
jp.add(jla);

jtf_username=new JTextField();
jtf_username.setBounds(50, 90, 250, 20);
jp.add(jtf_username);

JButton jbn=new JButton("登录");
jbn.setBounds(150, 130, 70, 20);
jp.add(jbn);

jbn.addActionListener(new ActionListener() {
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
String str=jtf_username.getText();
if(str!=null&&!str.equals("")){
if(loginFlag){
jtf_username.setText("用户名已登录");
}else{
String getusername=jtf_username.getText().trim();
ArrayList al=new ArrayList();
al.add("用户:"+getusername);
try {
oos.writeObject(al);
oos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
setVisible(false);
new ourFrame();
}
loginFlag = true;
}else{
jtf_username.setText("请输入用户名!");
}
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
class ourFrame extends JFrame{
/**
 * 
 */
private static final long serialVersionUID = 1L;
public ourFrame(){
  talkroom();
  }
private void talkroom() {
try {
setIconImage(ImageIO.read(Thread.currentThread().getContextClassLoader().getResource("logo.jpg")));
} catch (IOException e) {
e.printStackTrace();
}
setTitle("欢迎"+jtf_username.getText()+"来到聊天室");
setSize(600, 500);
setLocation(500, 100);
JPanel jp=new JPanel();
jp.setLayout(null);
add(jp);

show_jta=new JTextArea();
JScrollPane jsp = new JScrollPane(show_jta,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setBounds(5, 5, 400,350);
show_jta.setEditable(false);
jp.add(jsp);

JLabel jl=new JLabel("在线用户:");
jl.setBounds(410, 0, 80, 30);
jp.add(jl);

user_list=new JList();
user_list.setModel(new DefaultComboBoxModel(new String[] {""}));
JScrollPane jsp1 = new JScrollPane(user_list,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

jsp1.setBounds(410, 40, 170, 320);
jp.add(jsp1);

send_jtf=new JTextField();
send_jtf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
send();
}
});
send_jtf.setBounds(5, 380, 400, 50);
jp.add(send_jtf);

JButton jbn1=new JButton("发送");
jbn1.setBounds(300, 430, 80, 30);
jp.add(jbn1);
jbn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
send();
}
});

JButton jbn2=new JButton("退出");
jbn2.setBounds(400, 430, 80, 30);
jp.add(jbn2);
jbn2.addActionListener(new ActionListener() {
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
String exitusername=jtf_username.getText().trim();
ArrayList al=new ArrayList();
al.add("退出:"+exitusername);
try {
oos.writeObject(al);
oos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
}
 

解决方案 »

  1.   

    public void createsocketlogin() 开始对user_list初始化一下。
      

  2.   

    public void createsocketlogin(){
    try {
    user_list=new JList();
    user_list.setModel(new DefaultComboBoxModel(new String[] {""}));

    Socket socket=new Socket("localhost", 8765);
    oos=new ObjectOutputStream(socket.getOutputStream());
    new loginthread(socket).start();
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }