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

📄 listeners.java

📁 用java开发的聊天程序源代码 包含客户端文件和服务器文件
💻 JAVA
字号:
import java.io.*;
import java.awt.*;
import java.applet.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.net.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * 建立服务器
 * 等待连接
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class serverListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		SChattingMenu.mb_connect();
		SChattingFrame.showMessage("Waiting to be connected...");
		new ServerThread(SomethingStored.port).start();
	}
}

/**
 * 连接服务器
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class connectListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{		
			String str_ip;
			loop:
			while(true)
			{
				str_ip = JOptionPane.showInputDialog(ShowWindow.app,"Server IP Address:");
				try
						{	
							if(str_ip == null)str_ip = "127.0.0.1";	
							InetAddress host = InetAddress.getByName(str_ip);
							SomethingStored.host = host;
							Socket s = Connect.mb_client(host,SomethingStored.port);
							if(s == null) throw (new ConnectException());
							SomethingStored.s = s;
							SomethingStored.destIP = InetAddress.getByName(str_ip);
							SomethingStored.m_output = new ObjectOutputStream(s.getOutputStream());
							SomethingStored.m_input = new ObjectInputStream(s.getInputStream());
							SChattingFrame.writeSMessage(SMessage.MT_NAME,null,SomethingStored.userName,null);
						}
						catch(UnknownHostException ex)
						{
							JOptionPane.showMessageDialog(ShowWindow.app, "UnknownHost!!!", "alert", JOptionPane.ERROR_MESSAGE);
							continue loop;
						}
						catch(IOException ex)
						{
							SChattingMenu.mb_disconnect();
							SomethingStored.s = null;
							return;
						}
						catch(Exception exp)
						{
							System.err.println("Exception:"+exp);
							exp.printStackTrace();
							return;
						}
						break loop;
					}
			SChattingMenu.mb_connect();
			SChattingFrame.showMessage("Connected");
			SChattingFrame.audioPlay("connect.wav");
			new ReceiveThread().start();
	}
}

/**
 * 发送文本内容
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class sendListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		SMessage aMessage;
		String str = null;
		StyledDocument doc = null,docShow = null;
		
		
		//未连接时无法聊天
		if(SomethingStored.s == null)
		{
			JOptionPane.showMessageDialog(ShowWindow.app,"Not connected!!","Alert",JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		doc = SomethingStored.tp_write.getStyledDocument();
		docShow = SomethingStored.tp_show.getStyledDocument();
		try
		{
			if(doc.getLength() == 0)return;
			str = doc.getText(0,doc.getLength())+"\n";
			
			//docShow.insertString(docShow.getLength(),SomethingStored.userName + SMessage.getTime()+ ":\n",SomethingStored.defaultAttributeSet);		
			//docShow.insertString(docShow.getLength(),str,SomethingStored.myAttributeSet);
			//SomethingStored.tp_show.setCaretPosition(docShow.getLength());
			doc.remove(0,doc.getLength());
		}
		catch(BadLocationException err)
		{
			System.err.println("Exception:"+err);
			err.printStackTrace();
		}
		catch(Exception exp)
		{
			System.err.println("Exception:"+exp);
			exp.printStackTrace();
		}		
		aMessage = new SMessage(SMessage.MT_MESSAGE,SMessage.getTime(),str,SomethingStored.myAttributeSet);
		aMessage.append(SomethingStored.userName,SomethingStored.tp_show);
		try
		{
			SomethingStored.m_output.flush();
			SChattingFrame.writeSMessage(aMessage);
		}
		catch(IOException ioe)
		{
			System.err.println("IOException:"+ioe);
			ioe.printStackTrace();
		}
	}
}


		
/**
 * 关闭窗口
 * 退出程序
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class closeListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		Connect.mb_disconnect();
		System.exit(0);
	}
}

/**
 * 发送文件
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class fileListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		File f; 
		String fileName;
		String fileSize;
		
		
		if(SomethingStored.s == null)
		{
			JOptionPane.showMessageDialog(ShowWindow.app,"Not connected!!","Alert",JOptionPane.ERROR_MESSAGE);
			return;
		}
		if(SomethingStored.isSending)
		{
			JOptionPane.showMessageDialog(ShowWindow.app,"Somthing is sending,please wait a moment!!","Alert",JOptionPane.ERROR_MESSAGE);
			return;
		}
		JFileChooser chooser = new JFileChooser("C:"+File.separator);
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		int returnVal = chooser.showDialog(ShowWindow.app,"确定");
		
		
		if(returnVal == JFileChooser.APPROVE_OPTION) 
		{
			f = chooser.getSelectedFile();
			fileName = f.getName();
			fileSize = ""+f.length();
			try
			{
				SChattingFrame.writeSMessage(SMessage.MT_FILE,fileSize,fileName,null);
				
				SomethingStored.m_output.flush();
				SomethingStored.wait = new FileServerThread(f,SomethingStored.filePort,false);
				SomethingStored.wait.start();
			}
			catch(IOException ioe)
			{
				System.err.println("IOException"+ioe);
				ioe.printStackTrace();
			}
		}
		else if(returnVal == JFileChooser.CANCEL_OPTION)
		{
			return;
		}
	}
}

/**
 * 发送闪屏
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class shockListener implements ActionListener
{
	public static void mb_shock()
	{
		SChattingFrame app = ShowWindow.app;
		int count = 10;
		
		Rectangle r = app.getBounds();
		Rectangle temp_r = new Rectangle(r);
		
		int []xx ={ 0,0,1,1,0,0,-1,-1,0,0,1,1,0,0,-1,-1};
		int []yy ={ -1,-1,0,0,-1,-1,0,0,1,1,0,0,1,1,0,0};
		
		for(int j = 1;j<count;j++)
		for(int i = 0;i<xx.length;i++)
		{
			temp_r.x = r.x + 3*xx[i];
			temp_r.y = r.y + 3*yy[i];
			app.setBounds(temp_r);
			try
			{
				Thread.currentThread().sleep(10);
			}
			catch(InterruptedException ie)
			{
				return;

			}
		}
	}
	public void actionPerformed(ActionEvent ae)
	{
		SChattingFrame.audioPlay("nudge.wav");
		if(SomethingStored.s != null)
		{
			SChattingFrame.writeSMessage(SMessage.MT_SHOCK,null,null,null);
		}
		mb_shock();

	}
}

/**
 * 发送图片
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class pictureListener implements ActionListener
{
	public void actionPerformed(ActionEvent ae)
	{
		File f; 
		String fileName;
		String fileSize;
		
		
		if(SomethingStored.s == null)
		{
			JOptionPane.showMessageDialog(ShowWindow.app,"Not connected!!","Alert",JOptionPane.ERROR_MESSAGE);
			return;
		}
		if(SomethingStored.isSending)
		{
			JOptionPane.showMessageDialog(ShowWindow.app,"Somthing is sending,please wait a moment!!","Alert",JOptionPane.ERROR_MESSAGE);
			return;
		}
		JFileChooser chooser = new JFileChooser("C:"+File.separator);
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Images Files(*.jpg,*.gif,*.png)", "jpg", "gif", "png");
    chooser.setFileFilter(filter);
		int returnVal = chooser.showDialog(ShowWindow.app,"确定");
		
		if(returnVal == JFileChooser.APPROVE_OPTION) 
		{
			f = chooser.getSelectedFile();
			fileName = f.getName();
			StyledDocument doc = SomethingStored.tp_show.getStyledDocument();
		
			try
			{
				doc.insertString(doc.getLength(),SomethingStored.userName+":\n",SomethingStored.defaultAttributeSet);
				SChattingFrame.showPicture(doc.getLength(),f.getPath()); // 插入图片
				doc.insertString(doc.getLength(),"\n",SomethingStored.defaultAttributeSet);
				
				SChattingFrame.writeSMessage(SMessage.MT_PICTURE,"-1",fileName,null);
				SomethingStored.m_output.flush();
				new FileServerThread(f,SomethingStored.filePort,true).start();
			}
			catch(BadLocationException be)
			{
			}
			catch(IOException ioe)
			{
				System.err.println("IOException"+ioe);
				ioe.printStackTrace();
			}
		}
		else if(returnVal == JFileChooser.CANCEL_OPTION)
		{
			return;
		}
	}
}

/**
 * 存储历史记录
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class saveListener implements ActionListener
{
	
	public void actionPerformed(ActionEvent ae)
	{
		Vector<StyledDocument> doc = new Vector<StyledDocument> (5,5);
		File f = new File("history.dat");
		int length;
		
		StyledDocument temp_doc = null;
		ObjectInputStream in = null;
		try
		{
			if(!f.exists())f.createNewFile();
			in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)));
			while(true)
			{
				temp_doc = (StyledDocument)in.readObject();
				doc.addElement(temp_doc);
			}
		}
		catch(EOFException eof)
		{
		}
		catch(Exception e)
		{
			System.err.println("Exception:"+e);
			e.printStackTrace();
		}
		
		try
		{
			in.close();
		}
		catch(NullPointerException npe)
		{}
		catch(IOException ioe)
		{
		}
		length = doc.size();
		
		try
		{
			ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
		
			for(int i = 0;i < length;i++)
			{
				out.flush();
				out.writeObject(doc.elementAt(i));
			}
			out.writeObject(SomethingStored.tp_show.getStyledDocument());
			out.flush();
			out.close();
		}
		catch(IOException ioe)
		{
		}
		JOptionPane.showMessageDialog(ShowWindow.app, "Save successfully", "alert", JOptionPane.INFORMATION_MESSAGE);
	}
}

/**
 * 查阅历史记录
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class viewListener extends JDialog implements ActionListener
{
	JTextPane tp = null;
	JScrollPane sp = null;
	JButton b_prev = new SButton("Prev");
	JButton b_next = new SButton("next");
	JLabel l_index = new JLabel("0");
	Container c = null;
	int index = 0;
	int length = 0;
	Vector<StyledDocument> doc = new Vector<StyledDocument> (5,5);
	
	public viewListener()
	{
		super();
		
		c = getContentPane();
		c.setLayout(null);
		tp = new JTextPane();
		tp.setEditable(false);
		sp = new JScrollPane(tp);
		c.add(sp);
		c.add(b_prev);
		c.add(b_next);
		c.add(l_index);
		sp.setBounds(5,10,330,250);
		b_prev.setBounds(5,270,80,20);
		b_next.setBounds(255,270,80,20);
		l_index.setBounds(140,270,80,20);
		setSize(360,350);
		
		b_prev.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent ae)
			{
				if(index == 0)return;
				index--;
				tp.setStyledDocument(doc.elementAt(index));
				l_index.setText((index+1)+"/"+length);
				tp.repaint();
			}
		}
		);
		b_next.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent ae)
			{
				if(index == length-1)return;
				index++;
				tp.setStyledDocument(doc.elementAt(index));
				l_index.setText((index+1)+"/"+length);
				tp.repaint();
			}
		}
		);
		
	}
		
	public void actionPerformed(ActionEvent ae)
	{
		File f = new File("history.dat");
		StyledDocument temp_doc = null;
		ObjectInputStream in = null;
		try
		{
			if(!f.exists())f.createNewFile();
			in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)));
			while(true)
			{
				temp_doc = (StyledDocument)in.readObject();
				doc.addElement(temp_doc);
			}
		}
		catch(EOFException eof)
		{
		}
		catch(Exception e)
		{
			System.err.println("Exception:"+e);
			e.printStackTrace();
		}
		
		try
		{
			in.close();
		}
		catch(NullPointerException npe)
		{}
		catch(IOException ioe)
		{
		}
		length = doc.size();
		if(length == 0)
		{
			JOptionPane.showMessageDialog(ShowWindow.app, "no history", "alert", JOptionPane.ERROR_MESSAGE);
			return;
		}
		else
		{		
			tp.setStyledDocument(doc.elementAt(index));
			l_index.setText((index+1)+"/"+length);
			tp.repaint();
			setVisible(true);
		}
	}
	
}

/**
 * 清除历史记录
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class clearHistoryListener implements ActionListener
{
	public void actionPerformed(ActionEvent ae)
	{
		int res = JOptionPane.showConfirmDialog(ShowWindow.app,
						"Are you sure to delete history?","",JOptionPane.CANCEL_OPTION);
					if(res == JOptionPane.OK_OPTION)
					{
						File f = new File("history.dat");
						if(f.exists())f.delete();
						JOptionPane.showMessageDialog(ShowWindow.app, 
							"Delete successfully", "alert", JOptionPane.INFORMATION_MESSAGE);
						
					}		
					else return;
	}
}

/**
 * 背景音乐
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
class musicListener implements ActionListener
{
	private static boolean isPlaying = false;
	private static AudioClip sound = null;
	public void actionPerformed(ActionEvent ae)
	{
		String name = null;
		
		if(isPlaying)
		{
			sound.stop();
			isPlaying = false;
			return;
		}
		File f = new File("music");
		if(!f.exists())f.mkdir();
		JFileChooser chooser = new JFileChooser(new File("music").getAbsolutePath());
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Audio Files(*.au *.wav, *.mid)", "au", "wav", "aif", "aiff", "mid", "rmi");
    chooser.setFileFilter(filter);
		int returnVal = chooser.showDialog(ShowWindow.app,"确定");
		
		if(returnVal == JFileChooser.APPROVE_OPTION) 
		{
			name = chooser.getSelectedFile().getAbsolutePath();
			
			try
			{
				sound = Applet.newAudioClip(new URL("file:"+name));
			}
			catch(Exception e)
			{
				return;
			}
			sound.loop();
			isPlaying = true;
		}
	}
}

/**
 * 窗口配色
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */

class colorListener implements ActionListener
{
	public void actionPerformed(ActionEvent ae)
	{
		Color c = JColorChooser.showDialog(ShowWindow.app,"Choose a color",Color.white);
		SomethingStored.tp_show.setBackground(c);
	}
}

/**
 * 右键单击
 *
 * @author 戚荣波
 *
 * @version 1.0
 * @since J2SE 1.6
 */
 
class rightButtonClicked extends MouseAdapter
{
	boolean canEdit;
	public rightButtonClicked(boolean canEdit)
	{
		this.canEdit = canEdit;
	}
	public void mousePressed(MouseEvent e)
	{
		if(e.isPopupTrigger())
			SChattingFrame.pm.show(e.getComponent(),e.getX(),e.getY(),canEdit);
	}
	public void mouseReleased(MouseEvent e)
	{
		mousePressed(e);
	}
}

⌨️ 快捷键说明

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