⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatwindow.java

📁 一个用java编写的服务器,对于学习网络编程的人来说是个很好的例子
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * This file is part of the QuickServer library 
 * Copyright (C) 2003-2005 QuickServer.org
 *
 * Use, modification, copying and distribution of this software is subject to
 * the terms and conditions of the GNU Lesser General Public License. 
 * You should have received a copy of the GNU LGP License along with this 
 * library; if not, you can download a copy from <http://www.quickserver.org/>.
 *
 * For questions, suggestions, bug-reports, enhancement-requests etc.
 * visit http://www.quickserver.org
 *
 */

package chatserver.client;

import javax.swing.text.*;
import java.awt.Color;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Graphics;
import java.awt.event.*;

/**
 *
 * @author  Akshathkumar Shetty
 */
public class ChatWindow extends javax.swing.JFrame {
    private static Logger logger = Logger.getLogger(ChatWindow.class.getName());

	private ClassLoader classLoader = getClass().getClassLoader();
	public final ImageIcon logo = new ImageIcon(
		classLoader.getResource("chatserver/client/face-smile.gif"));
	public final ImageIcon smile = new ImageIcon(
		classLoader.getResource("chatserver/client/smile.gif"));
	public final ImageIcon sad = new ImageIcon(
		classLoader.getResource("chatserver/client/sad.gif"));
    
    private ChatRoom chatRoom;
    private LoginDialog loginDialog;
    private DefaultStyledDocument logDoc = null;
    private DefaultStyledDocument chatDoc = null;
    private DefaultListModel userListModel = null;
    private UserListListener userListListener = null;
    private Map styleMap = new HashMap();
    
    final String NORMALBLUE = "NormalBlue";
    final String BOLDBLUE = "BoldBlue";
    final String NORMALBLACK = "NormalBlack";
	final String ITALICBLACK = "ITALICBLACK";
    final String BOLDGREEN = "BoldGreen";
    final String NORMALRED = "NormalRed";
    final String ITALICRED = "ItalicRed";
    
	private InfiniteProgressPanel glassPane;
    
    /** Creates new form ChatWindow */
    public ChatWindow(ChatRoom chatRoom, String args[]) {
        this.chatRoom = chatRoom;
        setLogDoc(new DefaultStyledDocument());
        setChatDoc(new DefaultStyledDocument());
        setUserListModel(new DefaultListModel());
		prepareAllStyles();
        initComponents();
        userListListener = new UserListListener(userList);
        userList.addListSelectionListener(userListListener);
        loginDialog = new LoginDialog(this, args);
    }
    
    private void initComponents() {
        getContentPane().setLayout(new java.awt.BorderLayout(2, 2));
        setTitle("QuickChat - Please Login");
        
        buildChatPanel();
		buildSendMsg();
		buildLogPanel();
		buildUserListPanel();

		//---
		jPanel1 = new javax.swing.JPanel();
        jPanel1.setLayout(new java.awt.BorderLayout());
		jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH); //sendmsg

		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
			chatRoomScrollPane, jScrollPane1);
		splitPane.setOneTouchExpandable(true);
		java.awt.Dimension minimumSize = new java.awt.Dimension(500, 20);
		chatRoomScrollPane.setMinimumSize(minimumSize);
		splitPane.setDividerLocation(500);
		splitPane.setResizeWeight(0.9);

		jPanel1.add(splitPane, java.awt.BorderLayout.CENTER); //chat

		jTabbedPane1 = new javax.swing.JTabbedPane();
        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
        jTabbedPane1.addTab("Chat Room", jPanel1);
        jTabbedPane1.addTab("Logs", logTextScrollPane);

		getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        buildMenu();
		setIconImage(logo.getImage());

		addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
				 glassPane.interrupt();
                 System.exit(0);
             }
			 public void windowOpened(WindowEvent e) {			
			 }			
        });
        pack();
		setLocationRelativeTo(null);

		glassPane = new InfiniteProgressPanel("Logging to server..");
		setGlassPane(glassPane);
    }

    private void loginMenuItemActionPerformed(final java.awt.event.ActionEvent evt) {
		Thread t = new Thread() {
			public void run() {
				while(true) {
					if(login()==false) break;
					logger.info("Calling login()");
				}
			}
		};
		t.setPriority(Thread.NORM_PRIORITY);
        t.start();
    }
    
	private boolean login() {
		loginDialog.clearStatus();
        loginDialog.show();
        if(loginDialog.isOk()==true) {
            String r[] = loginDialog.getValues();
			glassPane.start();
			try {
				boolean flag = chatRoom.doLogin(r[0], Integer.parseInt(r[1]), 
					r[2], r[3]);				

				if(flag==true) {									
					enableChat(true);
				} else {
					enableChat(false);
					return true;//recall the login dialog
				}
			} catch(Exception ex) {
				enableChat(false);
				logger.warning("Error logging in : "+ex);
				return true;
			}
        }
		return false;
    }                                             
    
    private void logoutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		Thread t = new Thread() {
			public void run() {
				try {
					chatRoom.doLogout();
				} catch(Exception ex) {
					loginMenuItem.setEnabled(true);
					logoutMenuItem.setEnabled(false);
					logger.warning("Error logging in : "+ex);
				}
			}
		};
		t.setPriority(Thread.NORM_PRIORITY);
        t.start();
    }                                              
    
    private void sendTextActionPerformed(java.awt.event.ActionEvent evt) {                                         
       sendButtonActionPerformed(evt);
    }                                        
    
    private void sendPrivateButtonActionPerformed(java.awt.event.ActionEvent evt) {
		if(userListListener.getSelecteduser()==null) {
			setResponse("-ERR No User is selected!");
			return;
		}
		if(sendText.getText().length()==0) {
			setResponse("-ERR No message to send!");
			return;
		}
        chatRoom.sendPrivateMessage(userListListener.getSelecteduser()+"@"+chatRoom.getRoom(),
                sendText.getText());
        sendText.setText("");
    }                                                 
    
    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
		if(sendText.getText().length()==0) {
			setResponse("-ERR No message to send!");
			return;
		}
        chatRoom.sendMessage(sendText.getText());
        sendText.setText("");
    }                                          
    
    
    // Variables declaration - do not modify
    private javax.swing.JScrollPane chatRoomScrollPane;
    private javax.swing.JTextPane chatRoomTextPane1;
    private javax.swing.JMenu jMenu1, jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextPane logTextPane;
    private javax.swing.JScrollPane logTextScrollPane;
    private javax.swing.JMenuItem loginMenuItem;
    private javax.swing.JMenuItem logoutMenuItem;
	private javax.swing.JMenuItem exitMenuItem;
	private javax.swing.JMenuItem changeRoomMenuItem;
	private javax.swing.JMenuItem updateUserListMenuItem;
	private javax.swing.JMenuItem clearMenuItem;
	private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JButton sendButton;
    private javax.swing.JButton sendPrivateButton;
    private javax.swing.JTextField sendText;
    private javax.swing.JList userList;
    // End of variables declaration
    
    public void log(String msg) {
        logger.fine("Got: "+msg);
        try {
            AttributeSet style = (AttributeSet)styleMap.get(NORMALBLACK);
            getLogDoc().insertString(getLogDoc().getLength(),
                    msg +  "\n" ,style);
            
            //Point pt1=logTextPane.getLocation();
            Point pt2 = new Point((int)(0),
                    (int)(logTextPane.getBounds().getHeight()));
            logTextScrollPane.getViewport().setViewPosition(pt2);
        } catch(Exception e) {
            logger.warning("Error: "+e);
        }
    }
    
    public DefaultStyledDocument getLogDoc() {
        return logDoc;
    }
    
    public void setLogDoc(DefaultStyledDocument logDoc) {
        this.logDoc = logDoc;
    }
    
    
    
    public void prepareAllStyles() {
        SimpleAttributeSet aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.blue);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        styleMap.put(NORMALBLUE,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.blue);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        StyleConstants.setBold(aset, true);
        styleMap.put(BOLDBLUE,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.black);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        styleMap.put(NORMALBLACK,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.black);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
		StyleConstants.setItalic(aset, true);
        styleMap.put(ITALICBLACK,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset, new Color(0, 128, 0));
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        StyleConstants.setBold(aset, true);
        styleMap.put(BOLDGREEN,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.red);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        styleMap.put(NORMALRED,aset);

        aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset,Color.red);
        StyleConstants.setFontSize(aset,12);
        StyleConstants.setFontFamily(aset,"Verdana");
        StyleConstants.setItalic(aset, true);
        styleMap.put(ITALICRED,aset);
    }
    
    public void addChatMessage(String message) {
        logger.fine("Got: "+message);
        if(message.startsWith("{system.help} ")) {
            return;
        } else if(message.startsWith("{system.debug} ")) {
            //already logged
            return;
        }
        
        AttributeSet style = null;
        String fromid = null;
		String toid = null;
        
		String msgType = null;
        try {
            if(message.startsWith("{system.msg} ")) {
				msgType = "{system.msg}";
                message = message.substring(13);
                style = (AttributeSet)styleMap.get(BOLDBLUE);
            } else if(message.startsWith("{system.error} ")) {
				msgType = "{system.error}";
                message = "Error: "+message.substring(15);
                style = (AttributeSet)styleMap.get(NORMALRED);				
            } else if(message.startsWith("{user.msg:")) { 
				msgType = "{user.msg}";
				int j = message.indexOf(":", 10);//end of from
				int i = message.indexOf("} ", 10);
				if(j!=-1) {
					toid = message.substring(j+1, i);
				} else {
					j = i;
				}
                fromid = message.substring(10, j);
                message = message.substring(i+2);
                style = (AttributeSet)styleMap.get(NORMALBLUE);
            } else if(message.startsWith("{msg.user:")) { //gui command
				msgType = "{msg.user}";
                int i = message.indexOf("} ", 10);
                toid = message.substring(10, i);
                message = message.substring(i+2);
                style = (AttributeSet)styleMap.get(NORMALBLUE);
            } else if(message.startsWith("{user.info:")) {
				msgType = "{user.info}";
                int i = message.indexOf("} ", 11);
                fromid = message.substring(11, i);
                message = message.substring(i+2);
				if(message.equals("LoggedIn")) {
					addToUserList(fromid);
					message = "joined the room";
				} else if(message.equals("LoggedOut")) {
					removeFromUserList(fromid);
					message = "left the room";
				} else
					System.out.println("Unknown ->"+message+"<-");
                style = (AttributeSet)styleMap.get(ITALICBLACK);
            } else {
				msgType = "{unknown}";
                style = (AttributeSet)styleMap.get(NORMALBLACK);
            }
            

			if(msgType.equals("{user.msg}")) {
				toid = removeRoom(toid);
				fromid = removeRoom(fromid);
				if(toid!=null && toid.length()==0) {//to group
	                getChatDoc().insertString(getChatDoc().getLength(),
                        fromid+": ", (AttributeSet)styleMap.get(NORMALRED));
				} else if(toid!=null) {
					getChatDoc().insertString(getChatDoc().getLength(),
                        "PrvMsg From "+fromid+": ", (AttributeSet)styleMap.get(BOLDBLUE));
				}
			} else if(msgType.equals("{msg.user}")) {
				toid = removeRoom(toid);
                getChatDoc().insertString(getChatDoc().getLength(),
                        "PrvMsg To "+toid+": ", (AttributeSet)styleMap.get(BOLDBLUE));
            } else if(msgType.equals("{user.info}")) {
				fromid = removeRoom(fromid);
				getChatDoc().insertString(getChatDoc().getLength(),
                        fromid+": ", (AttributeSet)styleMap.get(NORMALRED));
			}
            
			if(message.indexOf(":-)")==-1 && message.indexOf(":-(")==-1) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -