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

📄 huffgui.java

📁 赫夫曼编译码器: 用哈夫曼编码进行通信可以大大提高信道利用率
💻 JAVA
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import structure.*;
import java.util.Iterator;
import java.io.*;
public class huffgui extends Frame
{
	String a="";
    
        Frame f=new Frame();
        Button btn=new Button("读入生成树:");
        Button btn11=new Button("编码读入:");
        Button btn12=new Button("译码读入:");
        Button btn2=new Button("编码结果");
        Button btn3=new Button("译码结果");
        Button btn4=new Button("退出");
        TextArea txt1=new TextArea();
        TextArea txt11=new TextArea();
        TextArea txt2=new TextArea();
        TextArea txt21=new TextArea();
        ButtonListener btnlistener=new ButtonListener();
        
	public huffgui()
    {
    	MyCanvas c=new MyCanvas();
		c.setBounds(0,20,800,600);
		c.setBackground(Color.cyan);
		
    	f.setLayout(null);
    	f.add(btn);
    	f.add(btn11);
    	f.add(btn12);
    	f.add(btn2);
    	f.add(btn3);
    	f.add(btn4);
    	f.add(txt1);
    	f.add(txt11);
    	f.add(txt2);
    	f.add(txt21);
    	
    	f.add(c);
    	btn.setBounds(30,80,100,40);
    	btn11.setBounds(30,30,100,40);//设置大小
    	btn12.setBounds(30,380,100,40);//设置大小
    	
    	btn2.setBounds(30,450,100,40);
    	btn3.setBounds(30,550,100,40);
    	btn4.setBounds(30,650,100,40);
    	  
    	txt1.setBounds(150,30,450,50); 
    	txt2.setBounds(150,380,450,50);	   	
    	txt11.setBounds(150,450,450,50);
    	txt21.setBounds(150,550,450,50);
    	btn.addActionListener(btnlistener);
    	btn11.addActionListener(btnlistener);
    	btn12.addActionListener(btnlistener);//监听
    	btn2.addActionListener(btnlistener);
    	btn3.addActionListener(btnlistener);
    	btn4.addActionListener(btnlistener);
    	btn.setForeground(Color.DARK_GRAY);
    	btn11.setForeground(Color.DARK_GRAY);
    	btn12.setForeground(Color.DARK_GRAY);//设置颜色
        btn2.setForeground(Color.DARK_GRAY);
        btn3.setForeground(Color.DARK_GRAY);
        btn4.setForeground(Color.DARK_GRAY);
        btn.setBackground(Color.GREEN);
        btn11.setBackground(Color.GREEN);
        btn12.setBackground(Color.GREEN);
        btn2.setBackground(Color.GREEN);
        btn3.setBackground(Color.GREEN);
        btn4.setBackground(Color.GREEN);
        
        setBackground(Color.YELLOW);//设置背景颜色(已被覆盖,转变为边框颜色)
        
    	f.setSize(700,750);
    	f.setTitle("HuffmanTree Demo");
    	
    	f.setVisible(true);
    	f.setResizable(false);
    	//使窗口能正常关闭        
        f.addWindowListener(new WindowAdapter()
        {
        	public void windowClosing(WindowEvent e)
        	{
        		System.exit(0);
        	}
        });
		
     }



class MyCanvas extends Canvas
{
	    MyCanvas()
	    {
		   setSize(50,500);
	    }
	    
	    
    public void paint(Graphics g)
	{  
		/*
		input "a good wood"
		encoding:
		a  100  1   
		g  101  1
		w  110  1
		d  111  2
		o  0    4
		*/
		g.setColor(Color.pink);
		/*String s1="100q";
	    String s2="11s";
		String s3="1010w";
		String s4="1011u";*/
		
		
	String	s1=a;
	String	s2="11s";
	String	s3="1010w";
		String	s4="1011u";
	for(int j=0;j<=3;j++)
    {	
		int y=70;
		String s="";
		if(j==0)s=s1;
		else if(j==1)s=s2;
		else if(j==2)s=s3;
		else if(j==3)s=s4;
		
		int index=0;
		int length=s.length();
		int x[]=new int[length+1];
		x[0]=270;
		g.fillOval(x[0],y,30,30);
		g.drawString("",265,82);
		x[index+1]=x[index];
		
		
		
		for(index=0;index<=length-2;index++)
		{char c=s.charAt(index);
		    
		  
			if(c=='1')
			{
				
				x[index+1]=x[index]+60;
				
				g.drawLine(x[index]+15,y+=15,x[index+1]+15,y+55);
				g.setColor(Color.black);
				g.drawString("1",(x[index+1]+15+x[index]+15)/2,y+35);
				g.setColor(Color.magenta);
				g.fillOval(x[index+1],y+=40,30,30);
			}
			else if(c=='0')
			{
			
		             
				
				
				
				
				x[index+1]=x[index]-50;
			g.drawLine(x[index]+15,y+=15,x[index+1]+15,y+55);
			g.setColor(Color.black);
				g.drawString("0",(x[index+1]+15+x[index]+15)/2,y+35);
				g.setColor(Color.BLUE);
				g.fillOval(x[index+1],y+=40,30,30);
				
			}

	
		if(index==length-2){g.setColor(Color.black);	 	
     if(j==0){g.drawString("q3",x[index+1]+15,y+15);}
	else if(j==1){g.drawString("s8",x[index+1]+15,y+15);}
	else if(j==2){g.drawString("w1",x[index+1]+15,y+15);}
	
	else if(j==3){g.drawString("u3",x[index+1]+15,y+15);}
	
	}	  
	    
		  
	    
	    
	    }
	
	
	
	
		   
    }
	
	
		g.setFont(new Font("txt",Font.BOLD+Font.ITALIC,28));
		
	   
		
		
	 }      
}



     private class ButtonListener implements ActionListener
     {
     	public void actionPerformed(ActionEvent e)
     	{
     		if(e.getActionCommand().equals("读入生成树:")){
     	
      a=JOptionPane.showInputDialog(null,"请输入字符串",null);
     		 
     		 
     		 
     		}
     	else if(e.getActionCommand().equals("编码读入:"))
     		{
     		   String x=txt1.getText();
     		   SinglyLinkedList freq = new SinglyLinkedList();
     	   for(int i=0;i<=x.length()-1;i++) 
           {char c = x.charAt(i);
	        if (c == '\n') break;
            leaf query = new leaf(c);
            leaf item = (leaf)freq.remove(query);
            if (item == null)
            {   // not found, add new leaf
                freq.addFirst(query);
            } else { // found, increment leaf
                item.frequency++;
                freq.addFirst(item);
            }
            }
             
        // insert each character into a Huffman tree
        Iterator li = freq.iterator();
        OrderedList trees = new OrderedList();
        while (li.hasNext())
        {
            trees.add(new huffmanTree((leaf)li.next()));
        }
    
        // merge trees in pairs until one remains
        Iterator ti = trees.iterator();
        while (trees.size() > 1)
        {
            // construct a new iterator
            ti = trees.iterator();
            // grab two smallest values
            huffmanTree smallest = (huffmanTree)ti.next();
            huffmanTree small = (huffmanTree)ti.next();
            // remove them
            trees.remove(smallest);
            trees.remove(small);
            // add bigger tree containing both
            trees.add(new huffmanTree(smallest,small));
        }
        // print only tree in list
        ti  = trees.iterator();
	    Assert.condition(ti.hasNext(),"Huffman tree exists.");
        huffmanTree encoding = (huffmanTree)ti.next();
        encoding.print();
        encoding.write();
        
          
      for(int i=0;i<=4;i++)
     { String o="";
       leaf nu=(leaf)freq.removeFirst();
	   try{
       FileReader fr = null;
           fr = new FileReader("C:/hfmTree.txt");
          //System.out.println(fr); 
       BufferedReader br=new BufferedReader(fr);
           //System.out.println(br);
       String Line = null;
           Line = br.readLine();
           //System.out.println(Line);
           
       while(Line!=null){
           o=Line;
           Line=null;
           br.close();
           fr.close();
       }
       //System.out.println(s);
       }catch(IOException e1){
           e1.printStackTrace();
       }
	       try{ 
      FileWriter fw=new FileWriter("C:/hfmTree.txt");

       fw.write(o+nu.frequency);
       fw.close();
     }catch(IOException exp){
      exp.printStackTrace();
   }
     String y="";
    try{
       FileReader fr = null;
           fr = new FileReader("C:/hfmTree.txt");
          //System.out.println(fr); 
       BufferedReader br=new BufferedReader(fr);
           //System.out.println(br);
       String Line = null;
           Line = br.readLine();
           //System.out.println(Line);
           
       while(Line!=null){
           y=Line;
           Line=null;
           br.close();
           fr.close();
       }
       //System.out.println(s);
       }catch(IOException e1){
           e1.printStackTrace();
       }
	   try{ 
       FileWriter fw=new FileWriter("C:/hfmTree.txt");
       fw.write(y+nu.ch);
       fw.close();
     }catch(IOException exp){
      exp.printStackTrace();
   }
        
     		   		    
     	    }	
     	
     	    }
     	     else if(e.getActionCommand().equals("编码结果")){
     	     	
     	        	        	String s="";       
	   try{
       FileReader fr = null;
           fr = new FileReader("C:/CodeFile.txt");
          //System.out.println(fr); 
       BufferedReader br=new BufferedReader(fr);
           //System.out.println(br);
       String Line = null;
           Line = br.readLine();
           //System.out.println(Line);
           
       while(Line!=null){
           s=Line;
           Line=null;
           br.close();
           fr.close();
       }
       //System.out.println(s);
       }catch(IOException e1){
           e1.printStackTrace();
       }
        txt11.setText(s);	
     	     	
     	     	
     	     }
     	    
     	    else if(e.getActionCommand().equals("译码读入:"))
     	    {
     	    	
     	    String r=txt2.getText();
     	    String s="";       
	       try{
           FileReader fr = null;
           fr = new FileReader("C:/hfmTree.txt");
          //System.out.println(fr); 
           BufferedReader br=new BufferedReader(fr);
           //System.out.println(br);
           String Line = null;
           Line = br.readLine();
           //System.out.println(Line);
           
           while(Line!=null){
           s=Line;
           Line=null;
           br.close();
           fr.close();
       }
       //System.out.println(s);
       }catch(IOException e1){
           e1.printStackTrace();
       }
       
       
       SinglyLinkedList freq = new SinglyLinkedList();
       for(int i=0;(2*i+1)<=s.length()-1;i++)
       {char t=s.charAt(2*i);
        int t1=Integer.parseInt(t+"");
        char ch=s.charAt(2*i+1);
        leaf query=new leaf(ch,t1);
        freq.addLast(query);
       }
       
        Iterator li = freq.iterator();
        OrderedList trees = new OrderedList();
        while (li.hasNext())
        {
            trees.add(new huffmanTree((leaf)li.next()));
        }
    
        Iterator ti = trees.iterator();
        while (trees.size() > 1)
        {
            ti = trees.iterator();
            huffmanTree smallest = (huffmanTree)ti.next();
            huffmanTree small = (huffmanTree)ti.next();
            trees.remove(smallest);
            trees.remove(small);
            trees.add(new huffmanTree(smallest,small));
        }
        ti  = trees.iterator();
	    Assert.condition(ti.hasNext(),"Huffman tree exists.");
        huffmanTree encoding = (huffmanTree)ti.next();
        

        String result="";
        BinaryTree temp2;
        temp2=encoding.root;
        BinaryTree record=new BinaryTree("");
        for(int i=0;i<=r.length()-1;i++)
       { char x=r.charAt(i);
        if(x=='0'){if(temp2.left()!=null) {temp2=temp2.left();
                     if(temp2.value()!="si"){ leaf z=(leaf)temp2.value();
                                             result=result+z.ch;
                                             record=temp2;
                                             temp2=encoding.root;}
                     else record=temp2;continue;}}
                     
                     
        else if(x=='1'){if(temp2.right()!=null) {temp2=temp2.right();
                      if(temp2.value()!="si"){leaf z=(leaf)temp2.value();
                                             result=result+z.ch;
                                             record=temp2;
                                             temp2=encoding.root;}
                      else record=temp2;continue;}}
              else if((x!='0')&&(x!='1')){ result=result+" 输入有误!";break;} 
     }
      if(record.value()=="si")  {result=result+" 输入有误!";} 
      try{ 
      FileWriter fw=new FileWriter("C:/TextFile.txt");
       fw.write(result);
       fw.close();
     }catch(IOException exp){
      exp.printStackTrace();
     }
        
        
        try{ 
      FileWriter w=new FileWriter("C:/hfmTree.txt");
       w.write("");
       w.close();
     }catch(IOException exp){
      exp.printStackTrace();
   }
     	    	
     	    }
     	    else if(e.getActionCommand().equals("译码结果"))
     	    {
     	    	
     	    	String y="";
	   try{
       FileReader fr = null;
           fr = new FileReader("C:/TextFile.txt");
          //System.out.println(fr); 
       BufferedReader br=new BufferedReader(fr);
           //System.out.println(br);
       String Line = null;
           Line = br.readLine();
           //System.out.println(Line);
           
       while(Line!=null){
           y=Line;
           Line=null;
           br.close();
           fr.close();
       }
       //System.out.println(s);
       }catch(IOException e1){
           e1.printStackTrace();
       }
       txt21.setText(y);
       try{ 
      FileWriter w=new FileWriter("C:/TextFile.txt");
       w.write("");
       w.close();
     }catch(IOException exp){
      exp.printStackTrace();
   }
     	    }
     	    else if(e.getActionCommand().equals("退出"))
     	    {
     	    	System.exit(1);
     	    }
     	
       }
    }

    public static void main(String args[])
	{
	   huffgui x=new huffgui();
	}
  }
   

⌨️ 快捷键说明

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