Tutorial: How to Create a Pie Chart IB

by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works




  • Tell a friend about this site (copy and paste the following HTML page that links to this tutorial.)
  • <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/PieChart/PieChart_IB_Tut.html"> Tutorial: Pie Chart IB </a>
    </table>
    </body>
    </html>
    Download Source
    and display a Screenshot
  • On-site classes can be arranged in Java and C++. Send all inquiries to:
  • RonHolland@sumtotalz.com
  • If you are having a problem viewing your DVD/CD ROM using Vista, try Restoring DVD/CD ROM
  • Introduction
  • Requirements
  • Application Template
  • init() Method
  • main() Method
  • Set the Height and Width
  • Create Buttons
  • Create Text Fields
  • Layout Managers
  • Graphics API
  • How Do We Get the User's Input?
  • Verifying Data are Digits
  • Verifying Data is not Null
  • Checking for Change in Data
  • Final Product
  • Template for an application/applet
  • Definitions

    Introduction

    This tutorial assumes that you have read and completed the following four tutorials.

    1. Your First Cup of Java
    2. Getting Started
    3. Tutorial: A Second Cup of Java .
    4. Tutorial: How to Create a Pie Chart I .
    The rest of this tutorial will build on and reinforce what you learned from the above tutorials.

    In the previous tutorial titled "Tutorial: How to Create a Pie Chart I", we explored the steps required to create a simple pie chart. In this tutorial, we will build on the previous example and allow the user to enter the data that we will use to create not only a pie chart, but also a bar chart. There are two ways that we could approach this project. One way would be to create an application; the other way is to create an applet. What if there was a third way to approach this project? What if we could write a program that could be executed as an application or as an applet? Let's pursue the following requirements to see how we approach this task.

    Requirements

    The requirements for this project are to:

    1. Create a program that can be run as an application or as an applet.
    2. Create this program as a subclass of the JApplet class.
    3. Display a pie chart using this program.
    4. Use JButtons should allow the user to select a pie chart or to allow for program shutdown.
      • Pie Chart
      • Exit
    5. Allow data to be entered via JTextFields.
    6. Use the Graphics API.
    7. Select a Layout Manager for the placement of the
      • JTextFields at the top
      • JButtons at the top
      • The pie chart in the center of the frame
    8. Create an application/applet template to outline your approach.

    Application Template

    What do we need to do to run this program as an application or as an applet?

    • The top-most class should extend JApplet.
    • There should be an init() method and not a constructor.
      • The init() method allows the program to run as an applet and perform any initialization.
    • There should be a main() method to allow the program to run as an application.
    • There should be an html file that allows the program to be loaded into a browser.
    With these points in mind, our application/applet pseudocode/template looks like:

      
    
    public class PieChart extends JApplet {
       
    
       public void init()   {    
       }
    
      /** allocate the text fields */
       public void setupText() {
    
       }
    
      /** allocate the buttons */
       public void setupButtons() {
    
       }
    
      /** set width of window */
       public void setWidth( int w )
          { width = ( w >= 0 ? w : 300 ); }
    
      /** set height of window */
       public void setHeight( int h )
          { height = ( h >= 0 ? h : 200 ); }
    
      /** ensure that all data is in digit format */
       public boolean  checkDigit(String strVal) {
       }
    
       /** check for any data changes in the text fields */
       public void checkFieldsChange( ActionEvent e ) {
       }
    
       /** get text values */
       public void getTextValues() {
       }
    
       /** Ensure that the data is not null */
       public boolean checkFields( ActionEvent e, 
                            JButton choice, int i )
       {
    
       }
    
       /** program entry point used by the JVM */ 
       public static void main( String args[] )
       {
          instantiate PieChart instance
    
          listen for window closing and exit
       }
    
    
       /** event handler for the buttons */
       private class ButtonHandler implements ActionListener {
       }
    
      /** event handler for the Text Fields */
       private class TextFieldHandler implements ActionListener {
       } 
    
    }
    
      
    Figure 1: Application/applet Pseudocode/template

    init() Method

    The init() method is called by the browser the user has loaded or by Java's applet viewer to inform this applet that it has been loaded into the system. The calling sequence when the applet is first loaded or reloaded is:

    • init() method
    • start() method.

    A subclass of Applet should override this method if it has initialization to perform. In this case, the PieChart_IB is a subclass of JApplet, and it calls other methods to create push buttons and text entry fields. In addition, the layout manager is created as part of the initialization process. An outline of what occurs looks like:

    1. setupPanels() - allocate the area on which the pie chart will be drawn
    2. setupText() - create the text entry fields
    3. setupButtons() - create the push button
    4. add the text fields to the top of the frame
    5. add the push buttons to the bottom of the frame
    6. add the drawing area to the center of the frame
    When you double-click on

    main() Method

    The main() method is called when PieChart_IB is run as an application. When the main() method is called, this method does the following:

    1. create and initialize the width and height variables
    2. create a JFrame object
    3. create one applet instance
    4. set the window's size (width and height)
    5. call applet's init and start methods
    6. attach applet to center of window
    7. add a Window Listener
      • Adds the specified window listener to receive window events from this window.
      • Add the windowClosing method
        • Invoked when a window is in the process of being closed. The close operation can be overridden at this point.
    8. make the window visible

    Set the Height and Width

    The purpose of the setHeight() and setWidth() methods is to set the frame's height and width, respectively.

    Create Buttons

    The setupButtons() method is used to create the push buttons used in this program.

    1. create the following push buttons
      • Create Pie Chart
      • Exit
    2. add the above buttons to the button panel
    3. add these buttons to the this event handler
      • This means that the Piechart_IB class will respond to the events caused by the Create Pie Chart or the Exit button being pressed.

    Create Text Fields

    The setupText() method allocates and sets up the label ("Enter 5 numbers.) and the entry text fields used to gather user input. It also allocates the JPanel that contains the text entry fields.

    1. create the following JPanel and entry text fields
      • textPanel
      • text1
      • text2
      • text3
      • text4
      • text5
    2. create an instruction label for the entry text fields
    3. add these entry text fields to the this event handler

    Layout Managers

    Why are we considering Layout Managers? When we are considering adding graphics to a frame, we need an anchor (context) that we can use as a reference for all of the graphics. The display area for a JApplet has a context, called a content pane to which the graphics must be attached if they are to be displayed at run time. To get the context in Java, we write a line similar to:

      
    Container c = getContentPane(); // get the context or content pane
      

    We are at a design point. We need to lay out the graphics in a precise order. Specifically, we need to have

    • Graphic at the top (North);
    • graphics (charts) in the Center;
    • One row at the bottom containing two graphic buttons (South);
    One Layout Manager per Container further complicates our design point. We overcome this latest problem by placing containers on our original container. These new containers are called JPanels.

    To layout the North graphics, we use code similar to the following.

      
    /** Declare and allocate the label field */ 
    JLabel label1      = new JLabel("Enter 4 numbers.");
    
    /** Declare and allocate the JPanel */ 
    JPanel textPanel   = new JPanel();
    
    /** Declare and allocate the text fields */ 
    JTextField text1   = new JTextField(5);
    JTextField text2   = new JTextField(5);
    JTextField text3   = new JTextField(5);
    JTextField text4   = new JTextField(5);
    JTextField text5   = new JTextField(5);
    
    /** Use the GridLayout Manager for the textPanel */
    textPanel.setLayout(
             new GridLayout( 1, 6 ) );
    
    /** Add the label and text fields to the textPanel */
    textPanel.add(label1);
    textPanel.add(text1);
    textPanel.add(text2);
    textPanel.add(text3);
    textPanel.add(text4);
    textPanel.add(text5);
    
    c.add( textPanel,  BorderLayout.NORTH );
      
    Figure 2: North graphics

    The code to create and add the buttons to the buttonPanel looks similar to the following.

      
    
    JButton pieButton     = new JButton( "Create Pie Chart" );
    JButton aboutButton   = new JButton( "Exit" );
    
    buttonPanel.add( pieButton ) ;
    buttonPanel.add( exitButton ) ;
      

    The code to add event handlers to the buttons looks similar to the following.

      
    pieButton.addActionListener( this ) ;
    exitButton.addActionListener( this ) ;
      
    Figure 3: Button Panel

    Graphics API

    We will be using aspects of the Graphics API, but not the entire API. The Graphics API is the fundamental class for rendering 2-dimensional shapes, text and images on the Java(tm) platform.

    • The primary Graphics method that we will use is the fillArc method. The fillArc method creates a pie-slice effect. Before we look at the fillArc method, let's review the drawOval method.

        
      public abstract 
             void drawOval(int x,
                           int y,
                           int width,
                           int height)
        
      Figure 4: drawOval Method


      • The drawOval method creates an outline of an oval. The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments.
      • The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.
      • Parameters:
        • x - the x coordinate of the upper left corner of the oval to be drawn.
        • y - the y coordinate of the upper left corner of the oval to be drawn.
        • width - the width of the oval to be drawn.
        • height - the height of the oval to be drawn.
      • If the width and the height are equal, the drawOval method will draw a circle.

      Now let's consider the fillArc method. When we call the API with the proper parameters, we hope to get a pie slice like the one shown in the following depiction.





        
      public abstract void 
                  fillArc(int x,           // (x, y) defines the 
                          int y,           //     origin of the arc
                          int width,       // width of the rectangle enclosing the oval
                          int height,      // height of the rectangle enclosing the oval
                          int startAngle,  // The arc is drawn from 
                          int arcAngle)    // startAngle to startAngle + 
                                           //     arcAngle.
        

      Figure 5: fillArc Method


      The pie chart will fill the entire 360° circle. In general, we will use the end of one angle sweep as the start of the next angle. For example, if the first pie-slice starts at zero and ends at 36°, then the next slice will start at 36°.
    • The color for a slice will be set with the following method.

        
      public abstract void setColor(Color c)
        
      Figure 6: setColor Method


        This method sets this graphics context's current color to the specified color. All subsequent graphics operations using this graphics context use this specified color.
    • We will use the following method to render text.
        
      public abstract void drawString(
            AttributedCharacterIterator iterator,
            int x,
            int y)
        
      Figure 7: sdrawString Method


      This method draws the text given by the specified iterator, using this graphics context's current color.

    Using the above methods and the Font class, we will create the Pie Chart Application as shown below.

    How Do We Get the User's Input?

    How do we get the user's input? We will use the method getText() to get the data the user-entered in each text field. In our example, we will get the data and store it in class ChartPanel's string variables. You will remember that we created an instance of DrwaPanel with the following code snippet:

      
    private ChartPanel myChart;
    
    myChart = new ChartPanel( width, height );
      

    To get and store the data, we will use the following code:
      
    strField1 = text1.getText() ;
    strField2 = text2.getText() ;
    strField3 = text3.getText() ;
    strField4 = text4.getText() ;
    strField5 = text5.getText() ;
      

    We will use the following code snippet to convert the user-entered data to integers.
      
    intField1 = Integer.parseInt( strField1 );
    intField2 = Integer.parseInt( strField2 );
    intField3 = Integer.parseInt( strField3 );
    intField4 = Integer.parseInt( strField4 );
    intField5 = Integer.parseInt( strField5 );
    
    NOTE: getText() returns the datathe user entered in the text field
      
    Figure 8: Obtainning User Input


    Verifying Data are Digits

    The checkDigit() method checks to ensure that the data entered in the text fields are all digits. The field is parsed character by character to ensure each is a digit. Since there are five entry fields, we need to check the data in each field. The Java API allows us to check one character at a time. We already have the data, in String format in the following fields:

    • strField1
    • strField2
    • strField3
    • strField4
    • strField5
    We will load the data into a String array and then use two for loops to parse the data. The Java API we will use looks like:

      
    Character.isDigit( strVal.charAt(iii) )
    
      a) 	isDigit(char ch)
              Determines if the specified character is a digit.
      b) 	charAt(int index)
              Returns the character at the specified index.
      
    Figure 9: Validating User Input


    The Character and String methods allow us to parse each character and determine whether it is a digit/number.

    Verifying Data is not Null

    The checkFields() method ensures that the data is not null. Why is it important to ensure that the data is not null/blank? If a filed is null/blank, the Integer.parseInt() method will fail. The logic used to check for a field being null/blank is:

      
    if ( strField1.equals("") ||
        strField2.equals("") ||
           strField3.equals("") ||
           strField4.equals("") ||
           strField5.equals("") )
      

    Figure 10: Validating User Input is not Null


    Checking for Change in Data

    The checkFieldsChange() method checks if data in the text fields has changed since the last check. The logic used to check for a field changed since last check is:

      
    if ( !(intField1 == chgField1 ) ||
           !(intField2 == chgField2 )  ||
             !(intField3 == chgField3 ) ||
             !(intField4 == chgField4 ) ||
             !(intField5 == chgField5 ) ) 
      

    The user data is obtained from the entry fields using the following logic.
      
    intField1 = Integer.parseInt( strField1  = text1.getText()  ) ;
    intField2 = Integer.parseInt( strField2  = text2.getText()  ) ;
    intField3 = Integer.parseInt( strField3  = text3.getText()  ) ;
    intField4 = Integer.parseInt( strField4  = text4.getText()  ) ;
    intField5 = Integer.parseInt( strField5  = text5.getText()  ) ;
      

    Figure 11: Checking for Change in Data


    Final Product

    Based on what we have learned, we can create a method summary and the final product, which are shown in the following sections..

    Method Summary
    PieChart_IB Class Method Summary
    Method Description
    actionPerformed() actionPerformed() is the event handler that responds to the events caused by pressing the buttons.
    checkDigit() checkDigit() This method checks to ensure that the data entered in the text fields are all digits.
    checkFields() the checkFields() method Ensure that the data is not null
    checkFieldsChange() The checkFieldsChange() method checks if data in the text fields has changed since the last check.
    getTextValues() The getTextValues() method retrieves data from the text entry fields.
    init() Initialization method init() calls the following methods:
    1. setupPanels() - creates the JPanels
    2. setupText() - creates lables and entry fields
    3. setupButtons() - creates push buttons
    4. In addition, it obtains the context for which to anchor the JPanels and add the GUI.
    main(String[] args) main(String args[] ) : this is the entry point for this application that Java calls when starting this program execution.
    setHeight(int h) Set the height to 600 if h less than 0
    setupButtons() The setupButtons() method allocates and sets up the JButtons.
    setupPanels() The setupPanels() methos is used to create the JPanles used in this application/applet.
    setupText() The setupText() method allocates and sets up the entry text fields and labels used to gather user input.
    setWidth(int w) Set the width of frame to 600 if w less than 0
    sysExit(int ext) The sysExit() method is called in response to a close application event.
    sysPrint() The sysPrint() method is used to print out debugging messages.

    Putting together what we have learned from the above, we get the following:

    PieChart_IB Final Product
      
    /** ***************************************************
     * File:  PieChart_IB
     * This file contains the code that creates a simple 
     * pie chart based on user data input.
     *
     ******************************************************/
    
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.awt.print.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.JOptionPane ;
    
    
    /** ***************************************************************
     *  class PieChart is used to create a simple pie chart based on
     *  user data input.
     **************************************************************** */
    public class PieChart_IB extends JApplet implements ActionListener {
       private Font         font;
       private JPanel buttonPanel, textPanel ;
       private JTextField text1, text2, text3, text4, text5 ;
       private Container c ;
       private int width = 500, height = 400;
       private int intField1 , intField2 , intField3 , intField4 , intField5 ;
       private int chgField1 = -1, chgField2 = -1 , chgField3 = -1 , chgField4 = -1 ,
                         chgField5 = -1 ;
       private JLabel label1;
       private JButton pieButton , exitButton ;
       private ChartPanel myChart ;
       private boolean debug = false , fieldNull , fieldNot_A_Digit , notInitPass = false;
       private String strField1 = "-1", strField2 = "-1", strField3 = "-1",
                           strField4 = "-1",  strField5 = "-1" ;
    
       /** ********************************************************
        * Initialization method init() calls the following methods:
        * 1- setupPanels() - creates the JPanels
        * 2- setupText() - creates lables and entry fields
        * 3- setupButtons() - creates push buttons
        *
        * In addition, it obtains the context for which to anchor
        * the JPanels and add the GUI.
        **********************************************************/
       public void init()   {
    
          setupPanels() ;
    
          setupText() ;
    
          setupButtons();
    
          c = getContentPane();
    
          c.add( textPanel,  BorderLayout.NORTH );
          c.add( buttonPanel, BorderLayout.SOUTH );
          c.add( myChart, BorderLayout.CENTER );
       }
    
       /**  ****************************************************
        *  The setupPanels() methods is used to create the JPanels
        *  and JLabels used in this application/applet.
        ********************************************************/
       public void setupPanels() {
          textPanel   = new JPanel();
          textPanel.setLayout(  new GridLayout( 1, 8 ) );
    
          buttonPanel = new JPanel();
    
          myChart = new ChartPanel( this );
    
       }
    
       /**  ****************************************************
        * The setupText() method allocates and sets up the entry
        * text fields used to gather user input.
        ********************************************************/
       public void setupText() {
    
          label1      = new JLabel("Enter 5 numbers.");
    
          text1       = new JTextField(5);
          text2       = new JTextField(5);
          text3       = new JTextField(5);
          text4       = new JTextField(5);
          text5       = new JTextField(5);
    
          textPanel.add( label1 );
          textPanel.add( text1  );
          textPanel.add( text2  );
          textPanel.add( text3  );
          textPanel.add( text4  );
          textPanel.add( text5  );
    
       }
    
       /**  ****************************************************
        * The setupButtons() method allocates and sets up the
        * JButtons.
        ********************************************************/
       public void setupButtons() {
          pieButton    = new JButton( "Create Pie Chart" ) ;
          exitButton   = new JButton( "Exit" ) ;
          exitButton.setBackground( Color.red);   ;
          exitButton.setForeground( Color.white);   ;
    
          buttonPanel.add( pieButton ) ;
          buttonPanel.add( exitButton ) ;
    
    
          pieButton.addActionListener( this ) ;
          exitButton.addActionListener( this ) ;
       }
    
       /**  ****************************************************
        * Set the width of frame to 600 if w less than 0
        ***************************************************** */
       public void setWidth( int w )
          { width = ( w >= 0 ? w : 600 ); }
    
       /** ****************************************************
        * Set the height to 600 if h less than 0
        ***************************************************** */
       public void setHeight( int h )
          { height = ( h >= 0 ? h : 400 ); }
    
    
       /**   ******************************************************
        * The checkFields() method ensures that the data is not null
        ***********************************************************/
       public boolean checkFields( ) {
          boolean checkedOK = false;
    
          sysPrint ( "checkFields() 1: Starting checkFields() method." ) ;
    
          strField1  = text1.getText()  ;
          strField2  = text2.getText()  ;
          strField3  = text3.getText()  ;
          strField4  = text4.getText()  ;
          strField5  = text5.getText()  ;
    
    
          if ( strField1.equals("") ||
                   strField2.equals("") ||
                   strField3.equals("") ||
                   strField4.equals("") ||
                   strField5.equals("") ) {
    
             JOptionPane.showMessageDialog(null,
                        "At least one of the entry fieds is null/blank.",
                        "Fields Cannot be Null", JOptionPane.INFORMATION_MESSAGE) ;
             fieldNull = true;
          }
          else if( !checkDigit()  ) {
    
             intField1 = Integer.parseInt( strField1 );
             intField2 = Integer.parseInt( strField2 );
             intField3 = Integer.parseInt( strField3 );
             intField4 = Integer.parseInt( strField4 );
             intField5 = Integer.parseInt( strField5 );
    
             fieldNot_A_Digit = true;
          }
          else
             repaint() ;
             checkedOK = true;
    
          return  checkedOK ;
       }
    
       /** ****************************************************
        * checkDigit()
        * This method checks to ensure that the data entered
        * in the text fields are all digits. The field is parsed
        * character by character to ensure each is a digit.
        ***************************************************** */
       public boolean  checkDigit( ) {
    
           int strLength = 0 , ii = 0 ;
           boolean isDig = true;
           String str , whichfield = "", strArray[] = { strField1 , strField2 ,
                               strField3 ,  strField4 , strField5 } ;
    
           for ( ii = 0; ii < 5 && isDig ; ii++) {
              String strVal = strArray[ ii ] ;
              strLength = strVal.length();
              sysPrint( "The value being checked is " + strVal +
                         " and the value of ii is " + ii + " and the length is " + strLength ) ;
    
              for (int iii = 0; iii < strLength; iii++) {
                 if (!Character.isDigit( strVal.charAt(iii) ) ) {
                    isDig = false;
    
                    switch ( ii ) {
                       case 0:
                          whichfield = "first" ;
                       break ;
                       case 1:
                          whichfield = "second" ;
                       break ;
                       case 2:
                          whichfield = "third" ;
                       break ;
                       case 3:
                          whichfield = "fourth" ;
                       break ;
                       case 4:
                          whichfield = "fifth" ;
                       break ;
                    }
    
                    JOptionPane.showMessageDialog(null,
                        "The number entered in the " + whichfield + " entry field is not a whole number." +
                        "\nPlease enter only whole numbers e.g. 55.",
                        "Fields Must ne Contain a number", JOptionPane.INFORMATION_MESSAGE) ;
                    break;
                 }
              }
           }
    
           intField1 = Integer.parseInt( strField1  ) ;
           intField2 = Integer.parseInt( strField2  ) ;
           intField3 = Integer.parseInt( strField3  ) ;
           intField4 = Integer.parseInt( strField4  ) ;
           intField5 = Integer.parseInt( strField5  ) ;
    
           return isDig;
       }
    
       /** **************************************************
        *  The checkFieldsChange() method checks if data in
        *  the text fields has changed since the last check.
        ****************************************************/
       public void checkFieldsChange( ActionEvent e ) {
    
           sysPrint ( "checkFieldsChange() 1: Starting checkFieldsChange() method." ) ;
    
           sysPrint ( "checkFieldsChange() 2: intField1 =s " + intField1 + " chgField1 =s " + chgField1 +
                       "\nintField2 =s " + intField2 + " chgField2 =s " + chgField2 +
                       "\nintField3 =s " + intField3 + " chgField3 =s " + chgField3 +
                       "\nintField4 =s " + intField4 + " chgField4 =s " + chgField4 +
                       "\nintField5 =s " + intField5 + " chgField5 =s " + chgField5   ) ;
    
           if ( !(intField1 == chgField1 ) ||
                      !(intField2 == chgField2 )  ||
                      !(intField3 == chgField3 ) ||
                      !(intField4 == chgField4 ) ||
                      !(intField5 == chgField5 ) ) {
    
              sysPrint ( "checkFieldsChange() 3: In checkFieldsChange() method." ) ;
    
              getTextValues() ;
    
              chgField1  = intField1 ;
              chgField2  = intField2 ;
              chgField3  = intField3 ;
              chgField4  = intField4 ;
              chgField5  = intField5 ;
           }
    
           return;
       }
    
       /**  **************************************************
        * The getTextValues() method retrieves data from the
        * text entry fields.
        ****************************************************/
       public void getTextValues() {
    
          sysPrint ( "getTextValues() 1: Starting getTextValues() method." ) ;
    
          intField1 = Integer.parseInt( strField1  = text1.getText()  ) ;
          intField2 = Integer.parseInt( strField2  = text2.getText()  ) ;
          intField3 = Integer.parseInt( strField3  = text3.getText()  ) ;
          intField4 = Integer.parseInt( strField4  = text4.getText()  ) ;
          intField5 = Integer.parseInt( strField5  = text5.getText()  ) ;
    
          repaint() ;
    
          return;
       }
    
    
       /** **************************************************
        *  actionPerformed() is the event handler that responds
        *  to the events caused by pressing the buttons. The events
        *  caused by pressing the push buttons are:
        *  1- Exit button causes the application to exit
        *  2- The Pie Button causes the application t0 gather the
        *     data the user entered to create a Pie Chart.
        ****************************************************/
       public void actionPerformed( ActionEvent e )  {
    
          if ( e.getSource() == exitButton ) {
                sysPrint ( "actionPerformed() 1: The exit button was pressed." ) ;
                System.exit( 0 );
          }
          else if ( e.getSource() == pieButton ) {
                sysPrint( "actionPerformed() 2: The create Pie Chart button was pressed." ) ;
                notInitPass = true ;
                sysPrint( "actionPerformed() 3: The value of notInitPass is " + notInitPass ) ;
                if ( checkFields( ) )
                   repaint() ;
                   //checkFieldsChange( e );
          }
       }
    
       /** ***********************************************************
        * The sysExit() method is called in response to a close
        * application event.
        ************************************************************* */
       public void sysExit( int ext ) {
          System.exit( ext ) ;
       }
    
       /** ****************************************************
        * sysPrint() is used to print out debugging messages.
        ***************************************************** */
       public void sysPrint( String str ) {
          if( debug )
             System.out.println( str ) ;
       }
    
       /** ********************************************************************
        *  main(String args[] ) : this is the entry point for this application
        *                         that Java calls when starting this program
        *                         execution when it runs as an application.
        *********************************************************************/
       public static void main( String args[] )
       {
          int width = 790, height = 550;
    
          // create window in which applet will execute
          JFrame appMain =
             new JFrame( "Pie Chart" );
    
          /** create one applet instance */
          final PieChart_IB appPie = new PieChart_IB();
          appPie.setWidth( width );
          appPie.setHeight( height );
    
    
          /** call applet's init and start methods */
          appPie.init();
          appPie.start();
    
          /** attach applet to center of window */
          appMain.getContentPane().add( appPie );
    
    
          appMain.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                {
                   appPie.sysExit( 0 );
                }
             }
          );
    
          /** set the window's size */
          appMain.setSize( appPie.width, appPie.height );
    
          /**
           * showing the window causes all GUI components
           * attached to the window to be painted
           */
    
          appMain.show();
       }
    
    
       /** ********************************************************
        *  subclass of JPanel to allow drawing in a separate area
        ***********************************************************/
       public class ChartPanel extends JPanel  {
          private PieChart_IB pcIB ;
    
          /** **************************************************
           *
           ****************************************************/
          public ChartPanel( PieChart_IB pc_IB ) {
    
             pc_IB.sysPrint("ChartPanel() 1: Entered. ") ;
             pcIB = pc_IB ;
    
          }
    
          /** ******************************************************
           *  paintComponent() is called when a paint operation is
           *                   required by the subclass MyPanel which
           *                   extends the JPanel class. The method
           *                   writes the help instructions on the
           *                   initial pass. It then does determines
           *                   a) - If any of the fields were null, which
           *                        will generate a fieldNull error.
           *                   b) - If any of the fields are not a digit,
           *                        which will generate a fieldNot_A_Digit
           *                        error.
           *
           *                   If steps a) and b) do not generate an error,
           *                   the code determines which button was pressed.
           *                   If currentChoice equals
           *
           *                   0- The pie chart button was pressed.
           *                   5- The exit button are not processed by this
           *                      paintcomponent because nothing needs to
           *                      be printed on the JPanel.
           ********************************************************/
          public void paintComponent( Graphics g )  {
    
             super.paintComponent( g );
    
             double floatVal[] = { 0.0, 0.0, 0.0, 0.0, 0.0 } ;
             double totVal = 0.0;
             Font font ;
    
             sysPrint("paintComponent() 1: Entered. The value of notInitPass is " + notInitPass ) ;
    
             if ( notInitPass ) {
    
                /** create 2D by casting g to Graphics2D */
                Graphics2D g2d = ( Graphics2D ) g;
    
                totVal   = (double) intField1 + intField2
                      + intField3 + intField4  + intField5  ;
                floatVal[0] = (double) (intField1 / totVal);
                floatVal[1] = (double) (intField2 / totVal);
                floatVal[2] = (double) (intField3 / totVal);
                floatVal[3] = (double) (intField4 / totVal);
                floatVal[4] = (double) (intField5 / totVal);
    
                sysPrint("paintComponent() 2: The value of intField1 is " + intField1 +
                          "\nintField2 is " + intField2  +
                          "\nintField3 is " + intField3  +
                          "\nintField4 is " + intField4  +
                          "\nintField5 is " + intField5 ) ;
    
                Arrays.sort (floatVal);
    
    
    
                /** draw 2D pie-shaped arc in white */
                g2d.setPaint( Color.white );
                g2d.setStroke( new BasicStroke( 6.0f ) );
                g2d.fillArc( 50, 80, 300, 300, 0,  (int) ( floatVal[ 4 ] * 360 ) );
                g2d.fillRect( 440, 80, 40, 20 )  ;
                g.setFont(
                        new Font( "", Font.BOLD + Font.ITALIC, 18 ) );
                g2d.setPaint( Color.black );
                g.drawString("- " +
                      (java.lang.Math.round( floatVal[ 4 ] * 100.0 ))   +
                         " %",  490, 95);
    
    
                g2d.setPaint( Color.green );
                g2d.fillArc( 50, 80, 300, 300, (int) ( floatVal[ 4 ] * 360 ),
                              ( int )( floatVal[ 3 ] * 360 ) );
                g2d.fillRect( 440, 120, 40, 20 )  ;
                g.setFont(
                        new Font( "", Font.BOLD + Font.ITALIC, 18 ) );
                g2d.setPaint( Color.black );
                g.drawString("- " + ( java.lang.Math.round( floatVal[ 3 ]  * 100))
                            + " %",  490, 135);
    
                g2d.setPaint( Color.blue );
                g2d.fillArc( 50, 80, 300, 300,
                      (int)(floatVal[ 4 ] * 360) +
                         (int)( floatVal[ 3 ] * 360 ) ,
                            (int)(floatVal[ 2 ] * 360 ) );
                g2d.fillRect( 440, 160, 40, 20 )  ;
                g.setFont(
                        new Font( "", Font.BOLD + Font.ITALIC, 18 ) );
                g2d.setPaint( Color.black );
                g.drawString("- " + ( java.lang.Math.round( floatVal[ 2 ]  * 100)) + " %",
                           490, 175);
    
                g2d.setPaint( Color.black );
                g2d.fillArc( 50, 80, 300, 300,
                      (int)(floatVal[ 4 ] * 360) +
                         (int)( floatVal[ 3 ] * 360 ) +
                            (int)( floatVal[ 2 ] * 360) ,
                               (int) (floatVal[ 1 ] * 360 ) + 2 ) ;
               g2d.fillRect( 440, 190, 40, 20 )  ;
               g.setFont(
                        new Font( "", Font.BOLD + Font.ITALIC, 18 ) );
                g2d.setPaint( Color.black );
                g.drawString("- " + ( java.lang.Math.round( floatVal[ 1 ]  * 100)) + " %",
                           490, 205);
    
                g2d.setPaint( Color.red );
                g2d.fillArc( 50, 80, 300, 300,
                      (int)(floatVal[ 4 ] * 360) +
                         (int)( floatVal[ 3 ] * 360 ) +
                            (int)( floatVal[ 2 ] * 360) +
                               (int)( floatVal[ 1 ] * 360) ,
                                  (int) (floatVal[ 0 ] * 360 ) + 2 ) ;
               g2d.fillRect( 440, 220, 40, 20 )  ;
               g.setFont(
                        new Font( "", Font.BOLD + Font.ITALIC, 18 ) );
                g2d.setPaint( Color.black );
                g.drawString("- " + ( java.lang.Math.round( floatVal[ 0 ]  * 100)) + " %",
                           490, 235);
    
                g2d.setStroke( new BasicStroke( 1.0f ) );
                g.drawArc( 50, 80, 300, 300, 0, 360 );
    
                notInitPass = true ;
             }
          }
       }
    }
    
    
      
    Figure 12: PieChart_IB Final Product

    Template for an application/applet

       
    /** this is a template for an application */
    
    
    import javax.swing.*;
    import java.awt.event.*;
    
    public class appAppletTemplate extends JApplet {
       /** class level variables */
       private int width = 500, height = 400;
    
       public void init() {
          
          setSize( 700, 400 ) ;
          setVisible( true ) ;
       }
    
       /** ***********************************************************
        * sysExit() is called when the application detects an
        *           event to cloase e.g., pressing the Exit button.
        ************************************************************* */
       public void sysExit( int ext ) {
          System.exit( ext ) ;
       }
     
       public static void main( String args[] ) {
    
          // create window in which applet will execute
          JFrame appMain =
             new JFrame( "Run as a app or an Applet" );
    
          /** create one applet instance */
          final appAppletTemplate appApp = new appAppletTemplate ();
          
          /** call applet's init and start methods */
          appApp.init();
          appApp.start();
    
          /** attach applet to center of window */
          appMain.getContentPane().add( appApp );
    
    
          appMain.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                {
                   appApp.sysExit( 0 );
                }
             }
          );
    
          /** set the window's size */
          appMain.setSize( appApp.width, appApp.height );
    
          /**
           * showing the window causes all GUI components
           * attached to the window to be painted
           */
    
          appMain.show();
       }
    
    }
    
      
    Figure 13: Template for an application/applet

    Definitions

    extends - when considering class MyClass extends ParentClass, MyClass inherits from ParentClass. Java does not support multiple inheritance; it supports only single inheritance.

    Graphics - The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto off-screen images.

    JFrame - A JFrame is a top-level window with a title and a border.

    override - replaces or redefines that behavior of the inherited method.

    Template - is a unique class or pattern that can be used to build other software code.

    Container - A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.

    JPanel - is a generic lightweight container.

    Layout Manager - Defines the interface for classes that know how to layout Containers.






  • HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

    © 2002 - =2016 All Rights Reserved Total Application Works