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

📄 mainframe.java

📁 java 聊天工具 包括服务器 和 客户端 类似
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Frame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTabbedPane;
import java.awt.Rectangle;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import javax.swing.JScrollPane;
import java.awt.GridBagConstraints;
import java.awt.FlowLayout;
import javax.swing.JButton;
public class MainFrame extends Frame {

	private static final long serialVersionUID = 1L;
	private JPanel jPanel = null;
	private JToolBar jToolBar = null;
	private JScrollPane jScrollPane1 = null;
	private JTextArea jTextArea = null;
	private JTabbedPane jTabbedPane = null;
	private JScrollPane jScrollPane = null;
	private JTextPane jTextPane = null;
	private JButton jButton = null;
	private JButton jButton1 = null;
	private JPanel jPanel1 = null;
	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	private JTextField jTextField = null;
	private JDesktopPane jDesktopPane = null;
	private JSplitPane jSplitPane = null;
	private JButton jButton2 = null;
	private JButton jButton3 = null;
	private JButton jButton4 = null;
	private JButton jButton5 = null;
	private JDesktopPane jDesktopPane1 = null;
	private JPanel jPanel2 = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel4 = null;
	private JList jList = null;
	private JScrollPane jScrollPane4 = null;
	private JButton jButton6 = null;
	private JButton jButton7 = null;
	//private JColorChooser jColorChooser = new JColorChooser(Color.black);
	
	private Socket socket;  //  @jve:decl-index=0:
	ObjectOutputStream objectOutputStream;
	ObjectInputStream objectInputStream;
	StreamData data,data2; //  @jve:decl-index=0:  
	String[] userList,myUserList;
	String myName = null;
	String toName = null;
	boolean login = false;
	Style def,sys,sys2,sys3;  //  @jve:decl-index=0:
	Color myTextColor = Color.black;  //  @jve:decl-index=0:
	int fontSize = 14;
	String fontFamily = "宋体";  //  @jve:decl-index=0:
	boolean msg = true;
	AudioClip currentAudio = null;
	private JButton jButton8 = null;
	private JButton jButton9 = null;
	private FaceChooser faceChooser = null;
	private JButton jButton10 = null;
	private JButton jButton11 = null;
	private JTextField jTextField2 = null;
	private JPasswordField jPasswordField = null;
	private UserInfo myUserInfo = null;
	private JLabel jLabel5 = null;
	private JScrollPane jScrollPane2 = null;
	private JLabel jLabel3 = null;
	private JButton jButton12 = null;
	/**
	 * This is the default constructor
	 */
	public MainFrame() {
		super();
		initialize();
		this.setVisible(true);
		start();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(616, 444);
		this.setTitle("Frame");
		this.setResizable(false);
		this.add(getJPanel(), BorderLayout.CENTER);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				StreamData exit;
				try{
					if(login){//退出前发信息通知服务器端
					int ret = JOptionPane.showConfirmDialog(null, "确定要退出?", "EXIT", JOptionPane.YES_NO_OPTION);
					if(ret == JOptionPane.NO_OPTION) return;//取消退出
					exit = new StreamData(jTextField.getText(),"ServerExit","TEXT",fontFamily,fontSize,0,new String("exit").getBytes(),(new String("exit").getBytes()).length);
					objectOutputStream.writeObject(exit);
					}
					}catch(Exception ioe){
						ioe.printStackTrace();
						JOptionPane.showMessageDialog(null, "失去连接!", "ERROR", JOptionPane.ERROR_MESSAGE);
						System.exit(1);
					}
				System.exit(1); // TODO Auto-generated Event stub windowClosing()
			}
		});		
	}
    
	private void start(){
		//System.out.println(jTabbedPane.getComponentAt(0));
		jTextField.requestFocus();
		//设置默认字体
		def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
		StyleConstants.setFontSize(def, 14);
		//设置系统字体
		sys = jTextPane.addStyle("sys", def);
		StyleConstants.setFontFamily(sys, "宋体");
		StyleConstants.setFontSize(sys, 12);
		StyleConstants.setForeground(sys, Color.blue);
		
		sys2 = jTextPane.addStyle("sys2", def);
		StyleConstants.setFontFamily(sys2, "宋体");
		StyleConstants.setFontSize(sys2, 12);
		StyleConstants.setForeground(sys2,new Color(-16738048));
		
		sys3 = jTextPane.addStyle("sys3", def);
		StyleConstants.setFontFamily(sys3, "宋体");
		StyleConstants.setFontSize(sys3, 12);
		StyleConstants.setForeground(sys3,Color.darkGray);
		
		faceChooser = new FaceChooser();
		for(int i=0;i<90;i++){
		faceChooser.jButtonList[i].addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				Object source = e.getSource();
				for(int i=0;i<90;i++){
					if(source == faceChooser.jButtonList[i]){
						jTextArea.append("<~>F"+Integer.toString(i)+"<~>");
					}
				}
				faceChooser.setVisible(false);
				// TODO Auto-generated Event stub actionPerformed()
			}
		});
		}
		
		try{ 
		while(!login)  //等待登陆
		Thread.currentThread().sleep(50);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			StreamData input;
			
			while(true){
		    if(socket.getInputStream().available()!=0) 
		    	Thread.currentThread().sleep(50);
		    input = (StreamData)objectInputStream.readObject();
		    //服务器端发来用户列表
		    //System.out.println(input.getFromName());
		    if(input.getFromName().equals(new String("Server"))){
		    	userList = StringOperate.stringToArray(new String(input.getBytes()));
		    	myUserList = StringOperate.arrayRemoveString(userList, new String(jTextField.getText()));
		    	jList.setListData(myUserList);
		    }else if(input.getFromName().equals(new String("ServerRename"))){
		    	JOptionPane.showMessageDialog(null, "该用户已经登录了!", "ERROR", JOptionPane.ERROR_MESSAGE);
				System.exit(1);
		    }else if(input.getFromName().equals(new String("ServerAgree"))){
		    	//JOptionPane.showMessageDialog(null, "hello!", "ERROR", JOptionPane.ERROR_MESSAGE);
		    	myUserInfo = UserInfo.getUserInfo(new String(input.getBytes()));
		    	Style newStyle = jTextPane.addStyle("newStyle", def);
		    	Style newStyle2 = jTextPane.addStyle("newStyle2", def);
				StyleConstants.setForeground(newStyle,Color.blue);
				StyleConstants.setForeground(newStyle2,Color.black);
				StyleConstants.setFontFamily(def, "宋体");
				StyleConstants.setFontSize(def, 16);
				Document doc = jTextPane.getDocument();
				    try{
				    	doc.insertString(doc.getLength(),"登录成功!\n\n",newStyle);
				    	doc.insertString(doc.getLength(),"以下是您的个人资料\n",newStyle);
				    	doc.insertString(doc.getLength(),"姓名:",newStyle);
				    	doc.insertString(doc.getLength(),myUserInfo.name+"\n",newStyle2);
				    	doc.insertString(doc.getLength(),"性别:",newStyle);
				    	doc.insertString(doc.getLength(),myUserInfo.sex+"\n",newStyle2);
				    	doc.insertString(doc.getLength(),"年龄:",newStyle);
				    	doc.insertString(doc.getLength(),myUserInfo.age+"\n",newStyle2);
				    	doc.insertString(doc.getLength(),"城市:",newStyle);
				    	doc.insertString(doc.getLength(),myUserInfo.city+"\n",newStyle2);
				    	doc.insertString(doc.getLength(),"Email:",newStyle);
				    	doc.insertString(doc.getLength(),myUserInfo.email+"\n",newStyle2);
				    }catch(BadLocationException ble){
				    	System.err.println("Couldn't insert initial text");
				    }
		    }else if(input.getFromName().equals(new String("ServerDisAgree"))){
		    	JOptionPane.showMessageDialog(null, "密码错误!", "ERROR", JOptionPane.ERROR_MESSAGE);
				System.exit(1);
		    }else if(input.getFromName().equals(new String("ServerNotExist"))){
		    	JOptionPane.showMessageDialog(null, "用户不存在!", "ERROR", JOptionPane.ERROR_MESSAGE);
				System.exit(1);
		    }else if(input.getFromName().equals(new String("newUserYES"))){
		    	jTextField.setText(myUserInfo.name);
		    	jPasswordField.setText(myUserInfo.password);
		    	jTextField.setEditable(false);
		    	jPasswordField.setEditable(false);
		    	
		    	JOptionPane.showMessageDialog(null, "注册成功!", "INFORMATION", JOptionPane.INFORMATION_MESSAGE);
		    	
		    	data = new StreamData(jTextField.getText(),"Server","TEXT",jPasswordField.getText(),fontSize,myTextColor.getRGB(),new String("Hello").getBytes(),((new String("Hello")).getBytes()).length);
				try{
				objectOutputStream.writeObject(data);
				}catch(Exception ioe){
					ioe.printStackTrace();
				}
		    }else if(input.getFromName().equals(new String("newUserNO"))){
		    	JOptionPane.showMessageDialog(null, "该用户名已经被占用!", "ERROR", JOptionPane.ERROR_MESSAGE);
				System.exit(1);
		    }
		    else if(input.getFromName().equals(new String("UserInfo"))){
		    	UserInfo userInfo = UserInfo.getUserInfo(new String(input.getBytes()));
		    	String userInfoString = "姓名:"+userInfo.name+"\n性别:"+userInfo.sex+"\n年龄:"+userInfo.age+"\n城市:"+userInfo.city+"\nEmail:"+userInfo.email;
		    	JOptionPane.showMessageDialog(null,userInfoString,userInfo.name+"的个人信息", JOptionPane.INFORMATION_MESSAGE);
		    }
		    else {//来自其它客户端的信息 输出部分
//		    如果标签不存在则创建
		    	File file= new File(".");
		    	if(msg){
		    		try{
		    			AudioClip msg = Applet.newAudioClip(new URL("file:/"+file.getAbsolutePath()+"/Audio/msg.mid"));
		    			msg.play();
		    			}
		    			catch(Exception e){
		    				e.printStackTrace();
		    			}
		    	}
			    boolean exist = false;
				for(int i=1;i<jTabbedPane.getTabCount();i++){
					if(jTabbedPane.getTitleAt(i).equals(input.fromName)){
					exist = true;
					break;
					}
				}
				if(exist == false){
				   JScrollPaneWithText jSText = new JScrollPaneWithText();
				   jTabbedPane.addTab(input.fromName, null, jSText, null);
				}
		    ///************************************************************
		    //设置 相关信息后输出
		    if(input.getDataType().equals(new String("TEXT"))){//得到的是文本信息
		    	//System.out.println(input.getDataType());
		   // Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
		   // Style newStyle = jTextPane.addStyle("newStyle", def);
		   // StyleConstants.setForeground(newStyle,new Color(input.rgb));
		    //StyleConstants.setFontFamily(def, "黑体");
		    //StyleConstants.setFontSize(def, 20);
		    
		  //  Document doc = jTextPane.getDocument();
		 //   try{
		 //   	doc.insertString(doc.getLength(), new String(input.getBytes()).concat(new String("\n")),newStyle);
		//	    jTextPane.removeStyle("newStyle");
		//    }catch(BadLocationException ble){
		//    	System.err.println("Couldn't insert initial text");
		    //}
		    ////////////////////////////////////////////////////////////////
		    
			//得到目标面版并输出
			JScrollPaneWithText current = null;
			for(int i=1;i<jTabbedPane.getTabCount();i++){
				if(jTabbedPane.getTitleAt(i).equals(input.fromName)){
					 if(jTabbedPane.getComponentAt(i) instanceof JScrollPaneWithText){
						  current = (JScrollPaneWithText)jTabbedPane.getComponentAt(i);
					 }
					 break;
				}
			}
			
			String[] show = new String(input.getBytes()).split("<~>");
			
		    Style newStyle = current.getJTextPane().addStyle("newStyle", def);
		    StyleConstants.setForeground(newStyle,new Color(input.rgb));
		    
		    StyleConstants.setFontFamily(newStyle,input.getFontFamily());
		    StyleConstants.setFontSize(newStyle,input.getFontSize());
		    
		    Document doc = current.getJTextPane().getDocument();
		    try{
		    	doc.insertString(doc.getLength(),input.getFromName().concat(GetTime.currentTime().concat(new String("\n"))), sys);
		    	//doc.insertString(doc.getLength(), new String(input.getBytes()).concat(new String("\n")),newStyle);
		    	//*********************************************************************
		    	for(int i=0;i<show.length;i++){
		    		if(show[i].length()==2&&show[i].charAt(0)=='F'&&show[i].charAt(1)>='0'&&show[i].charAt(1)<='9'){
		    		    int index = Integer.parseInt(Character.toString(show[i].charAt(1)));
		    			//System.out.println(index);
		    			Style newImageStyle = current.getJTextPane().addStyle("newImageStyle", def);
		    			StyleConstants.setIcon(newImageStyle, new ImageIcon("Face\\"+Integer.toString(index)+".gif"));
		    			StyleConstants.setAlignment(newImageStyle,StyleConstants.ALIGN_LEFT);
		    			doc.insertString(doc.getLength()," ",newImageStyle);
		    		}
		    		else if(show[i].length()==3&&show[i].charAt(0)=='F'&&show[i].charAt(1)>='0'&&show[i].charAt(1)<='9'&&show[i].charAt(2)>='0'&&show[i].charAt(2)<='9'){
		    			int tempIndex = Integer.parseInt(Character.toString(show[i].charAt(1)));
		    			int tempIndex2 = Integer.parseInt(Character.toString(show[i].charAt(2)));
		    			int index = 10*tempIndex+tempIndex2;
		    			//System.out.println(index);
		    			Style newImageStyle = current.getJTextPane().addStyle("newImageStyle", def);
		    			StyleConstants.setIcon(newImageStyle, new ImageIcon("Face\\"+Integer.toString(index)+".gif"));
		    			StyleConstants.setAlignment(newImageStyle,StyleConstants.ALIGN_LEFT);
		    			doc.insertString(doc.getLength()," ",newImageStyle);
		    		}
		    		else{
		    			doc.insertString(doc.getLength(), show[i], newStyle);
		    		}
		    	}
		    	doc.insertString(doc.getLength(),"\n", newStyle);
		    	//*********************************************************************
			    current.getJTextPane().setCaretPosition(current.getJTextPane().getDocument().getLength());
			    //System.out.println(sBar.getMaximum());
		    }catch(BadLocationException ble){
		    	System.err.println("Couldn't insert initial text");
		    }
		    }
		    // 文本信息部分结束
		    else if(input.getDataType().equals(new String("IMAGE"))){//得到的是图片信息	    
			    //***********************************得到面板并输出
			    JScrollPaneWithText current = null;
				for(int i=1;i<jTabbedPane.getTabCount();i++){
					if(jTabbedPane.getTitleAt(i).equals(input.fromName)){

⌨️ 快捷键说明

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