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

📄 cw2e.java

📁 samll awt programs for the beginner.
💻 JAVA
字号:
/**
* Author: Jing Han
* Date; 12/11/03
*Module: G6DICp
* Title: ICP Coursework 2
* SCSiT Username: jxh23m
*/


import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;




class MainWindow extends Frame
{
     static String title;
     static Vector angle;
     static String fname;
     static Vector data;
     static Vector label;
     

    MenuItem openItem, quitItem;
    FileDialog openFileDialog = new FileDialog (this);

    //window listener,set up close window event
    class ListenToWindow extends WindowAdapter
    {
         public void windowClosing(WindowEvent event)
         {
            quit();
         }
     }//end of windowlistener


    //menu listener:set up menu events and select event
    class ListenToMenu implements ActionListener
    {
        public void actionPerformed (ActionEvent e)
        {
            Object whatmenu=e.getSource();
            if(whatmenu==openItem) open();
            if(whatmenu==quitItem) quit();
           
        }
    }

    //open method: get file name and construct dostuff method
    private void open()
    {
        openFileDialog.setVisible(true);
        fname=openFileDialog.getDirectory()+openFileDialog.getFile();
        if(fname!=null)
        doStuff();
    }
    
    
    //quit method: close window and set up quit item function
    private void quit()
    {
        setVisible(false);
        dispose();
        System.exit(0);
    }

    
    private void doStuff()
    {
               
        //declare varialbe title and instantiate vector
        title = "";
        data=new Vector();
        angle=new Vector();
        double sum=0;
        Double myDouble;
        double datavalue; 
        label=new Vector();
  
       //instantiate RandomAeccessFile. myData file is opened for reading
        
        try 
        {
            RandomAccessFile inFile=new RandomAccessFile(fname,"r");
            String line; //a string to contain the line read
            int lineNo=0;//initialise the line number of file
          /*----------------------------------------------------------------  
            *use the readLine method to read a line into the string line 
            until the end of the file
            *convert string line into Integer and cast Integer to vector object
            * use lineNo to track line number for seperate the title input from vector input
            *catch I/o error
            ---------------------------------------------------------------*/
            while((line=inFile.readLine())!=null) 
            {
               
                if( lineNo == 0 )
                {
                    title=line;
                 }
                 //start read second line and skip empty line until the end of the empty line
                 else if(lineNo!=0&& line.length()!=0)
                 {
                 	//trim line, start	
                    String newline=line.trim();
                    //counter the index of the first occurence of space between
                    int x=newline.indexOf(" ");
				   	String firststr=newline.substring(0,x);
					//wrap string data into vector
				   	myDouble=Double.valueOf(firststr);    
                    datavalue=myDouble.doubleValue(); 
                    //caculate the angle  
                    sum=sum+datavalue;        
                    data.addElement(myDouble); 
                 
                    //get the string sequence into Vector label
                 	int y=newline.lastIndexOf(" ");
			  		String secondstr=newline.substring((y+2),(newline.length()-1));
                 	label.addElement(secondstr);
                  }
                   
                 lineNo++; 

            }//end of while loop 
         }// end of try 
         catch (IOException e)
         {
            System.out.println("An i/o error has occured ["+e+"]");
         }// end of catch exception

       /*---------------------------------------------------------------------------------
        *  instatiate new vector angle and delacare new variables
        * cast data in the vector to do caculation
        * wrap the result double number to Double and put into vector angle
        ---------------------------------------------------------------------------------*/
        Double tmpValue;             
        double value;                 
        double angleDouble;           
        int angleInt;
        Double myD;
         
        for(int n=0;n<data.size();n++)
        {
            
          tmpValue=(Double)data.elementAt(n);  
          value=tmpValue.doubleValue();             
          angleDouble=Math.round(360*value/sum);    
          myD=new Double(angleDouble);
          angleInt=myD.intValue();
          angle.addElement(new Integer(angleInt));  
         
         }
         
        //set up panel and add panel into mainwindow
        DrawPanel myPanel=new DrawPanel(angle,data,title);      
        myPanel.setBackground(Color.white);
        myPanel.setBounds(10,10,500,500);

        add(myPanel);                                          
        
        int y=0;
        int yy;
       
          //create label and set up text in vector label     
         for(int n=0;n<label.size();n++)
         {
            Label myLabel=new Label();
            y=n*20+110;
            myLabel.setText((String)label.elementAt(n));
            myLabel.setFont(new Font("SansSerif",Font.BOLD,12));
            myLabel.setBounds(100,y,50,30);
            
            myPanel.add(myLabel);
            myLabel.setAlignment(myLabel.CENTER);
			//create other label for legend box
            Label otherLabel=new Label();
            yy=n*20+290;
            otherLabel.setText((String)label.elementAt(n));
            otherLabel.setFont(new Font("SansSerif",Font.BOLD,12));
            otherLabel.setBounds(110,yy,50,30);
            myPanel.add(otherLabel);
            otherLabel.setAlignment(otherLabel.CENTER);

         }
         
       }// end of doStuff
    
    
    /*---------------------------------------------------------------------------------
     *MainWindow method for set up mainwindow all the component 
     * set up window component:menubar, menu item,
     *bound the component to mainwindow
     *register function of window and menubar
     *--------------------------------------------------------------------------------*/
    public MainWindow()
    {
       //disable layout manager
        setLayout(null); 

         //set up window                                       
        setSize(640,550);                                      
        setBackground(Color.gray);
        setTitle("Pie Chart");

        //set up file dialog
        openFileDialog.setMode(FileDialog.LOAD);                
        openFileDialog.setTitle("Open");

        //create menubar
        MenuBar myMenuBar=new MenuBar();                        
        Menu fileMenu=new Menu("File");
        Menu helpMenu=new Menu("Help");

         //create menu item
        openItem=new MenuItem("Open");                         
        quitItem=new MenuItem("Quit");
        
        //add item to menu
        fileMenu.add(openItem);                                 
        fileMenu.add(quitItem);

         //add menus to menu bar
        myMenuBar.add(fileMenu);                               
        myMenuBar.add(helpMenu);

         //add menubar to frame
        setMenuBar(myMenuBar);    
                            
        //menu listener
        ListenToMenu handleMenu=new ListenToMenu();
        openItem.addActionListener(handleMenu);
        quitItem.addActionListener(handleMenu);

        //window listener
        ListenToWindow HandleWindow=new ListenToWindow();
        addWindowListener(HandleWindow);   

     } //end of mainwindow
       

}//end of mainwindow class

/*----------------------------------------------------------------------------------------------
 *instatiate panel instance
 *draw circle,title, data into panel
 *draw legend box and legend into panel
 *----------------------------------------------------------------------------------------------*/
class DrawPanel extends Panel
    {
        Vector angle;
        Vector data;
        String title;
        
        //constructor
        public DrawPanel(Vector a,Vector b,String t)
        {
            angle = a; 
            data=b; 
            title=t;
                
        }
        
        //paint method draw circle, legend box,all strings and fill the color accordingly
        public void paint(Graphics g)
        {
        
            super.paint(g);
        	//draw title and legend into panel 
            g.setFont(new Font("SansSerif",Font.BOLD,20)); 
            g.setColor(Color.blue);
            g.drawString(title,80,90);
            g.setColor(Color.black);
            g.setFont(new Font("SansSerif",Font.BOLD,14));      
            g.drawString("Legend",100,280);                     
            String tmpstr;
            int y;
            
            //draw  number of vector data
            for(int n=0;n<data.size();n++)
            {
                g.setColor(Color.red);
                g.setFont(new Font("SansSerif",Font.BOLD,14));
                tmpstr=((Double)data.elementAt(n)).toString();
                y=n*20+130;
                g.drawString(tmpstr,60,y);
                            
            }
        
            /*---------------------------------------------------------------------
             *fill circle according to angle
             *split the circle and fill the color
             *use for loop to change startArc and arcAngle
             *Math.random method to get random color int number
             *draw legend rectangle and fill the color as circleArch;
             ---------------------------------------------------------------------*/
            int startAngle=0;
            int tmpArc;
            int a;
            int b;
            int c;
            Double tempA;
            Double tempB;
            Double tempC;
            
            //use random colour draw pie chart and legend box
            for(int n=0;n<angle.size();n++)
            {
                
                tempA = new Double(Math.random()*255);
                a = tempA.intValue();
                tempB = new Double(Math.random()*255);
                 b= tempB.intValue();
                tempC = new Double(Math.random()*255);
                c = tempC.intValue();
            
                tmpArc=((Integer)angle.elementAt(n)).intValue();               
                g.setColor(new Color(a,b,c));
                g.fillArc(300,100,140,140,startAngle,tmpArc);                 
                startAngle=tmpArc+startAngle;                                      
                y=n*20+300;                                                   
                g.fillRect(80,y,10,10);                                        
            
            }
            
        }
        
        
}//end of DrawPanel class

/*-------------------------------------------------------------------
 *main class 
 *show mainwindow
 *------------------------------------------------------------------*/
class cw2e
{
    public static void main(String args[])
    {
        MainWindow myWindow=new MainWindow();
        myWindow.show();
    }
}//end of main class

⌨️ 快捷键说明

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