Tutorial: How to Create a Pie Chart II

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






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

© 2002 - 2013 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://www.sumtotalz.com/TotalAppsWorks/PieChart/PieBarChart_Tut_II.htm"> Tutorial: Pie Chart II </a>
    </table>
    </body>
    </html>
    Source
    Screenshot
  • On-site classes can be arranged in Java and C++. Send all inquiries to:
  • RonHolland@sumtotalz.com
  • New: How to create a basic Toolbar application.
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III
  • If you are having a problem viewing your DVD/CD ROM using Vista, try Restoring DVD/CD ROM
  • Introduction
  • Requirements
  • What is the purpose of the setup() method?
  • What is the data?
  • 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

    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 .
    5. Tutorial: How to Create a Pie Chart IB .
    The rest of this tutorial will build on and reinforce what you learned from the above tutorials, especially the Tutorial: How to Create a Pie/Bar Chart IB. We will expand on the Pie/Bar Chart IB by adding to its behaviors/functionality

    In the previous tutorial titled "Tutorial: How to Create a Pie Chart IB", we explored the steps required to allow the user to enter the data that we used to create a 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 this data can also be used to create 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:

      Requirements for Pie Chart IB

    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 ( BorderLayout) for the placement of the
      • JTextFields at the top
      • JButtons at the top
      • The pie chart in the center of the frame
    8. Add the following behaviors
      • The setupButtons() method allocates and sets up the JButtons.
      • The setupPanels() method is used to create the JPanels and JLabels used in this application/applet.
      • The setupText() method allocates and sets up the entry text fields used to gather user input.
      • Check Fields - the checkFields() method ensures that the data in the entry fields is not null
      • Check Digits - checkDigit() This method checks to ensure that the data entered in the text fields are all digits.
      • Check Fields that Change - The checkFieldsChange() method checks if data in the text fields has changed since the last check.
    9. Create an application/applet template to outline your approach.

      New Requirements for Pie Chart II

    10. Add to the Chart IB behaviors with the addition of
      • Create a Bar Chart behavior
        • Use the data the user has entered to create a Bar chart.
      • Create a Help behavior
        • Display a HTML file that will provide help explanations on several aspects of how to create and run this application.
      • Create a About behavior
        • Create a link to the Total Application Works home page.
      • Create a Clear behavior
        • Clear the center panel of any images.
    11. The push button array should resemble

      Create a Pie Chart Create a Bar Chart Help About Clear Exit

    In the following section, we will describe the purpose of the setup() method.

    What is the purpose of the setup() method?

    The purpose of the setup() methods is to create the GUI the user sees displayed. In some previous tutorials, I used the setup() method to create

    • JMenus - An implementation of a menu -- a popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar.
    • JMenuBars - An implementation of a menu bar.
    • JMenuItems - An implementation of an item in a menu.
    • JLabels - A display area for a short text string or an image, or both.
    • JPanels - is a generic lightweight container.
    • JScrollBars - An implementation of a scrollbar.
    • JTables - The JTable is used to display and edit regular two-dimensional tables of cells.
    • JTextAreas - A JTextArea is a multi-line area that displays plain text.
    • JTextFields - JTextField is a lightweight component that allows the editing of a single line of text
    The above object creation takes place in the setup() method. Some of you might prefer further step-wise refinement. If so, the outline might look like:
    1. The setupMenu() method allocates and sets up the JMenu, JMenuBar, and JMenuItems.
    2. The setupButtons() method allocates and sets up the JButtons.
    3. The setupPanels() method is used to create the JPanels and JLabels used in this application/applet.
    4. The setupText() method allocates and sets up the entry text fields used to gather user input.
    The above logic takes place in the setup() method and is used to create the context so that user can interact with the application/applet.

      
    private void setUp() {
       SetupMenu() ;
       SetUPButtons() ;
       SetUPPanels() ;
       SetupText() ;
    
    }
    private void SetupMenu() {
       ...
    }
    private void SetUPButtons() {
       ...
    }
    private void SetUPPanels()  {
       ...
    }
    private void SetupText()  {
       ...
    }
      
    Figure 1: Setup() method


    This process was/is known as top-down structured programming. What I have done is take a unit (setup() method), and I have broken it down into finer units. It is like taking a dime and turning it into ten pennies. The pennies are still worth ten cents; the same value that the dime has. Some of you might also prefer this granularity because in future versions of this tutorial, I remove the SetUPButtons() method and replace it with the SetUPMenu() method. Even though I do this replacement in the context of the original Setup() method, this finer granularity makes it easier to see what I have done. In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

      
              +--------------+
              |      Data    |  
              +-------+------+  
                      ^
                      |
                      V
              +-------+------+
              |   Top-down   |  
              |  Structured  |<----+
              |  programming |     |
              |  on Classes  |     | (step-wise)
              |  and methods |     | (refinement)
              +--------------+     | (as needed) 
                      |            |
                      +------------+ 
     
      
    Figure 2: Holland's OOP Programming Design Model
    Let's look at the data in the next section.

    What is the data?

    What is the data? In the context of this tutorial, the data is entered via the JTextfields on the main frame. There are five JTextfields, so there are

    • Five pieces of data, and
    • Data in the form of whole numbers (ints)
    The behaviors that we want to perform on this data is:
    • checkDigit() - This method checks to ensure that the data entered in the text fields are all digits.
    • checkFields() - the checkFields() method ensures that the data is not null
    • checkFieldsChange() - This method checks if data in the text fields has changed since the last check.
    • drawBar() - uses the user input to draw the bar chart.
    • drawPie() - uses the user input to draw the pie chart
    • getTextValues() - This method retrieves the user entered data from the text entry fields.
    The logic follows in the form of:
    1. The Pie Chart application/applet starts execution;
    2. The user enters five whole (ints) numbers;
    3. The user presses a push button;
      • If the user pressed Create a Pie chart or Create a Bar chart,
        • The program gathers the data;
        • The program ensures that there is data in each field;
        • If so, the program ensures that each piece of data is an integer;
        • The program determines whether the data has changed since the last push button was pressed;
        • If there are no data errors, the program proceeds;
    4. The program performs the request indicated by the button pressed;
    5. The program waits for the next user request.
    Based on understanding the data, we can then define the tasks to be performed on this data. We will describe the class that will enclose these behaviors/methods in the next section.

    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 actionPerformed( ActionEvent e ) {
       }
    }
    
      
    Figure 3: 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
      
    Figure 4: Getting the context

    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 5: Laying out the North Panel

    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 ) ;
      
    Figure 6: Laying out the Button Panel

    The code to add event handlers to the buttons looks similar to the following.
      
    pieButton.addActionListener( this ) ;
    exitButton.addActionListener( this ) ;
      
    Figure 7: Adding an actionlistener

    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 8: 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.

      Figure 9: Depiction of calling fillArc


      Below is the fillArc API.

        
      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 10: 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.

    • The color for a slice will be set with the following method.

        
      public abstract void setColor(Color c)
        
      Figure 11: 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 12: drawString 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 DrawPanel 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 13: Getting 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 14: Verifying data is a digit


    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 15: Verifying data 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 ) ) 
      
    Figure 16: Checking for Change in Data


    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 17: Getting User 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_II 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
    PieChart_II Final Product
      
    /** ***************************************************
     * File:  PieChart_II
     * This file contains the code that creates a simple 
     * pie chart based on user data input.
     *
     */
    
    /** ***************************************************
     * File:  PieChart_II
     * This file contains the code that creates a simple
     * pie chart based on user data input.
     *
     *
     * Copyright (c) 2002-2006 Advanced Applications Total Applications Works.
     * (AATAW)  All Rights Reserved.
     *
     * AATAW grants you ("licensee") a non-exclusive, royalty free, license to use,
     * modify and redistribute this software in source and binary code form,
     * provided that i) this copyright notice and license appear on all copies of
     * the software; and ii) licensee does not utilize the software in a manner
     * which is disparaging to AATAW.
     *
     * This software is provided "AS IS," without a warranty of any kind. All
     * express or implied conditions, represntations and warranties, including any
     * implied warranty of merchantability, fitness for a particular purpose or
     * non-INFRINGEMENT, are hereby excluded. AATAW and its licensors shall not be
     * liable for any damages suffered by licensee as a RESULT of using, modifying
     * or distributing the SofTWare or its derivatives. In no event will AATAW or its
     * licensors be liable for any lost revenue, profit or data, or for direct,
     * indirect, special, consequential, incidental or punitive damages, however
     * caused and regardless of the theorY of liability, arising OUT of the use of
     * or inability to use software, even if AATAW has been advised of the
     * possibility of such damages.
     *
     * This software is not designed or intended for use in on-line control of
     * aircraft, air traffic, aircraft navigation or aircraft communications; or in
     * the design, construction, operation or maintenance of any nuclear
     * facility. licensee represents and warrants that it will not use or
     * redistribute the Software for such purposes.
     */
    
    
    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_II extends JApplet implements ActionListener {
       private JFrame app ;
       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 butChoice = -1  ;
       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 , barButton , helpButton , aboutButton ,
                               clearButton ,  exitButton ;
       private ChartPanel myChart ;
       private boolean debug = true , 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() method 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" ) ;
          barButton    = new JButton( "Create Bar Chart" ) ;
          helpButton   = new JButton( "Help" ) ;
          aboutButton  = new JButton( "About" ) ;
          clearButton  = new JButton( "Clear" ) ;
          exitButton   = new JButton( "Exit" ) ;
          helpButton.setBackground( Color.blue ) ;
          helpButton.setForeground( Color.white ) ;
          aboutButton.setBackground( Color.blue ) ;
          aboutButton.setForeground( Color.white ) ;
          clearButton.setBackground( Color.white ) ;
          clearButton.setForeground( Color.blue ) ;
          exitButton.setBackground( Color.red ) ;
          exitButton.setForeground( Color.white ) ;
    
          buttonPanel.add( pieButton ) ;
          buttonPanel.add( barButton ) ;
          buttonPanel.add( helpButton ) ;
          buttonPanel.add( aboutButton ) ;
          buttonPanel.add( clearButton ) ;
          buttonPanel.add( exitButton ) ;
    
          pieButton.addActionListener( this ) ;
          barButton.addActionListener( this ) ;
          helpButton.addActionListener( this ) ;
          aboutButton.addActionListener( this ) ;
          clearButton.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 ); }
    
       /** ****************************************************
        * Set the current value of the frame reference
        ***************************************************** */
       public void setFrameRef( JFrame appM )
          { app = appM ; }
    
       /**   ******************************************************
        * 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( ) ) {
                butChoice = 0 ;
                repaint() ;
             }
          }
          else if ( e.getSource() == barButton ) {
             sysPrint( "actionPerformed() 4: The create Bar Chart button was pressed." ) ;
             notInitPass = true ;
             sysPrint( "actionPerformed() 5: The value of notInitPass is " + notInitPass ) ;
             if ( checkFields( ) ) {
                butChoice = 1 ;
                app.setTitle( "Bar Chart" );
                repaint() ;
             }
          }
          else if ( e.getSource() == helpButton ) {
             sysPrint( "actionPerformed() 6: The help button was pressed." ) ;
             File hd = new File("..//PieChart_II_Help.html");
    
             Runtime rt = Runtime.getRuntime();
             String[] callAndArgs = { "c:\\Program Files\\Internet Explorer\\IEXPLORE.exe" ,
                             "" + hd.getAbsolutePath() };
    
    
             butChoice = 2 ;
             try {
                Process child = rt.exec(callAndArgs) ;
                child.waitFor();
                sysPrint ("Process exit code is: " +
                                     child.exitValue());
             }
             catch(IOException e2) {
                sysPrint(
                      "IOException starting process!");
             }
             catch(InterruptedException e3) {
                sysPrint( "Interrupted waiting for process!" ) ;
             }
          }
          else if ( e.getSource() == aboutButton ) {
             sysPrint( "actionPerformed() 7: The about button was pressed." ) ;
             Runtime rt = Runtime.getRuntime();
             String[] callAndArgs = { "c:\\Program Files\\Internet Explorer\\IEXPLORE.exe" ,
                               "http://www.sumtotalz.com/TotalAppsWorks/index.html" };
    
             butChoice = 3 ;
             try {
                Process child = rt.exec(callAndArgs) ;
                child.waitFor();
                sysPrint ("Process exit code is: " +
                                     child.exitValue());
             }
             catch(IOException e2) {
                sysPrint(
                      "IOException starting process!");
             }
             catch(InterruptedException e3) {
                sysPrint( "Interrupted waiting for process!" ) ;
             }
          }
          else if ( e.getSource() == clearButton ) {
             sysPrint( "actionPerformed() 8: The clear button was pressed." ) ;
             butChoice = 4 ;
             text1.setText("")  ;
             text2.setText("")  ;
             text3.setText("")  ;
             text4.setText("")  ;
             text5.setText("")  ;
    
             repaint() ;
          }
       }
    
       /** ***********************************************************
        * The sysExit() method is called in response to a close
        * application event.
        ************************************************************* */
       public void sysExit( int ext ) {
          System.exit( ext ) ;
       }
    
       /** **************************************************
        * drawPie uses the user input to draw the pie chart
        ****************************************************/
    
          public void drawPie( Graphics g) {
    
             double floatVal[] = { 0.0, 0.0, 0.0, 0.0, 0.0 } ;
             double totVal = 0.0;
             Font font ;
    
                /** 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 ;
          }
    
       /** **************************************************
        * drawBar uses the user input to draw the bar chart
        ****************************************************/
       public void drawBar( Graphics g) {
          /** create 2D by casting g to Graphics2D */
          Graphics2D g2d = ( Graphics2D ) g;
    
                /** Draw the x-coordinate line */
          g.setColor(Color.black);
          g.drawLine ( 5, 406, 450, 406);
    
                /** draw 2D Bars in red */
          g2d.setColor( Color.red );
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 50, 400 - intField1, 5,
                       intField1 ) );
          g.drawString("Red ", 45,
                       400 - intField1 - 40);
          g.drawString("" + intField1, 45,
                       400 - intField1 - 20);
    
          g2d.setColor( Color.green );
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 100, 400 - intField2,
                            5, intField2) );
          g.drawString( "Green ", 90,
                    400 - intField2 - 40);
          g.drawString( "" + intField2, 90,
                    400 - intField2 - 20);
    
          g2d.setColor( Color.yellow );
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 150, 400 - intField3,
                         5, intField3 ) );
          g.drawString("Yellow ", 140,
                              400 - intField3 - 40);
          g.drawString("" + intField3, 140,
                              400 - intField3 - 20);
    
          g2d.setColor( Color.blue );
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 200, 400 - intField4,
                        5, intField4 ) );
          g.drawString("Blue " , 190,
                          400 - intField4 - 40);
          g.drawString("" + intField4 , 190,
                          400 - intField4 - 20);
    
          g2d.setColor( Color.white );
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 250, 400 - intField5,
                        5, intField5 ) );
          g.drawString("White " , 240,
                          400 - intField5 - 40);
          g.drawString("" + intField4 , 240,
                          400 - intField5 - 20);
       }
       /** ****************************************************
        * 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_II appPie = new PieChart_II();
          appPie.setWidth( width );
          appPie.setHeight( height );
          appPie.setFrameRef( appMain ) ;
          /** 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_II pcII ;
    
          /** **************************************************
           * The ChartPanel( PieChart_II pc_II ) method is a constructor for the
           * ChartPanel class.
           ****************************************************/
          public ChartPanel( PieChart_II pc_II ) {
    
             pc_II.sysPrint("ChartPanel() 1: Entered. ") ;
             pcII = pc_II ;
    
          }
    
          /** ******************************************************
           *  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.
           *                   1- The bar chart button was pressed.
           *                   2- The help button was pressed.
           *                   3- The about button was pressed.
           *                   4- The clear 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 );
    
             sysPrint("paintComponent() 1: Entered. The value of notInitPass is " + notInitPass ) ;
    
             if ( notInitPass ) {
    
                switch ( butChoice ) {
                   case 0:
                      drawPie( g )  ;
                   break ;
                   case 1:
                      drawBar( g )  ;
                   break ;
                }
             }
          }
       }
    }
    
    
      

    Template for an application/applet

    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();
       }
    
    }
    
      

    Container -

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

    JButton -

    JLABEL -

    JMenu -

    JMenuBar -

    JMenuItems -

    JPanel -

    JScrollBar -

    JTable -

    JTextAreas -

    JTextFields -

    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 ]

    © 2002 - 2013 All Rights Reserved Total Application Works