Tutorial: How to Create a Pie/Bar Chart III
by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my site

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


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works



  • Tell a friend about this site (copy and paste the following link or send this page to a friend.)

                            Link to this tutorial                    
    <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a
    href="http://www.sumtotalz.com/TotalAppsWorks/PieChart/PieBarChart_Tut_III.htm"> Tutorial: Pie Chart III </a>
    </table>
    </body>
    </html>
    source
    screenshot


  1. Java Table of contents

    Java Resources

  2. Java: Getting started
  3. Java: Introduction
  4. Java: Variables - TBS
  5. Java: Enumeration Types - TBS
  6. Java: Arrays - TBS
  7. Java: Strings - TBS
  8. Java: Formatted Output - TBS
  9. Java: Modulus - TBS
  10. Java: classes
  11. Java: Stacks - TBS
  12. Java: Queues - TBS
  13. Java: Trees - TBS
  14. Java Encapsulation
  15. Conditional Statement : If-Else - TBS
  16. Loop Control Statement : For Loop - TBS
  17. Loop Control Statement : While Loop - TBS
  18. Java: File I/O - TBS
  19. Java:Functions - TBS
  20. Java: Inheritance
  21. Java: Introduction to Switch constructs
  22. 2nd Java Cup, includes MyCalc
  23. Applet Life Cycle Tutorial
  24. MultiThreaded Tutorial
  25. Thread Life Cycle
  26. Pie Chart I
  27. Pie/Bar Chart IB
  28. Pie/Bar Chart II
  29. Pie/Bar Chart III
  30. A Basic Calculator
  31. Linked Lists
  32. Linked List II
  33. Linked List III
  34. Linked List IV
  35. Hardware Store I
  36. Hardware Store II
  37. Hardware Store III
  38. Client/Server
  39. Client/Server II
  40. Client/Server III
  41. Client/Server IV
  42. Multithreaded Client/Server
  43. Multithreaded Client/Server II
  44. Multithreaded Client/Server III
  45. Basic Calculator II
  46. Basic Calculator III

Introduction

This tutorial assumes that you have read and completed the following six 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 .
  6. Tutorial: How to Create a Pie Chart II .
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 II. We will expand on the Pie/Bar Chart II 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 a pie chart, and use this data to create a bar chart. The additional behavior that will be added in this tutorial will be to allow the user to print the pie chart or bar chart shown on the screen. The method we will use to display the pie and/or bar chart on the screen will be a combination program that can 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 an HTML file that provides 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

    New Requirements for Pie Chart III

  12. Add a print function to the application.
  13. Add a print push button to the application.
  14. The push button array should look like the following:
    Create a Pie Chart Create a Bar Chart Print 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 the Windows Explorer listing of PieBarGraph, Java will load the application and use the main() method as an entry point into the application.

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
    • Create Bar Chart
    • Print
    • Help
    • About
    • Clear
    • Exit
  2. add the above buttons to the button panel
  3. add these buttons to the this event handler
    • This means that the PieBarGraph class will respond to the events caused by the Create Pie Chart, Create Bar 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: application/applet pseudocode/template

What does context mean?
What does context mean? The content pane is the area where the developer is allowed to add items like push buttons, text, etc.

  
             Title Bar            
 _ 
  
 X  
                  Menu Bar    
                  Tool Bar    



contentPane





Figure 5: contentPane

Content c = in Figure 4 declares a container upon which other objects can be added.

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

  • Graphic (text fields) at the top (North);
  • graphics (charts) in the Center;
  • One row at the bottom containing seven 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 6: Declaring Text Fields

We are using the BorderLayout Manager. A border layout manager lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER.

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

  

pieButton    = new JButton( "Create Pie Chart" ) ;
barButton    = new JButton( "Create Bar Chart" ) ;
printButton  = new JButton( "Print" ) ;
helpButton   = new JButton( "Help" ) ;
aboutButton  = new JButton( "About" ) ;
clearButton  = new JButton( "Clear" ) ;
exitButton   = new JButton( "Exit" ) ;

buttonPanel.add( pieButton ) ;
buttonPanel.add( barButton ) ;
buttonPanel.add( printButton ) ;
buttonPanel.add( helpButton ) ;
buttonPanel.add( aboutButton ) ;
buttonPanel.add( clearButton ) ;
buttonPanel.add( exitButton ) ;

c.add( buttonPanel,  BorderLayout.SOUTH );
  
Figure 7: Declaring Push Buttons

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

  
pieButton.addActionListener( this ) ;
barButton.addActionListener( this ) ;
printButton.addActionListener( this ) ;
helpButton.addActionListener( this ) ;
aboutButton.addActionListener( this ) ;
clearButton.addActionListener( this ) ;
exitButton.addActionListener( this ) ;
  
Figure 8: Event Handlers

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 9: 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 10: 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 11: 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 12: 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 13: 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.

Print the Charts

How do we print the rendered charts? First, we create a class that implements the class Printable.

  
class DrawPanel extends JPanel implements Printable {
  

Next we create code to start a print job.
  
/** Start a new print job */
job = PrinterJob.getPrinterJob() ;
job.setPrintable( this );
if ( job.printDialog()) {
   try {
      job.print();
   }
   catch (PrinterException e) {
      e.printStackTrace();
   }
}
  
Figure 14: Creating Print Dialog


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 15: Creating Text Fields


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 16: Verifying Data


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 17: 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 18: Determing whether data has changed


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 19: Obtaining User data


The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. parseInt(String s) parses the string argument and creates a signed decimal integer.

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
Figure 20: PieChart_III Class Method Summary
Method Description
actionPerformed() actionPerformed() is the event handler that responds to the events caused by pressing the buttons. The events
  1. caused by pressing the push buttons are:
  2. Exit button causes the application to exit
  3. The Pie Button causes the application to gather the data the user entered to create a Pie Chart.
  4. The Pie Button causes the application to gather the data the user entered to create a Bar Chart.
  5. The Print Button causes the application to print the the chart being displayed.
  6. The Help Button causes the application to call the Internet Explorer to display a Help file.
  7. The About Button causes the application to try to connect to my site.
  8. The Clear Button causes the application to clear any chart being displayed and the text entry fields.
checkDigit() checkDigit() This method checks to ensure that the data entered in the text fields are all digits.
  1. Obtain each value in order
  2. Determine the length of each value in order
  3. Parse is value a character at a time
  4. If value is not a digit, determine which field return value indicating value is not a digit
  5. Otherwise, indicate all values are digits
checkFields() the checkFields() method Ensure that the data is not null
  1. Obtain the data from each field
  2. Determine if any field is null
  3. Verify that each piece of data is a digit
checkFieldsChange() The checkFieldsChange() method checks if data in the text fields has changed since the last check.
drawBar() drawBar uses the user input to draw the bar chart
drawPie() drawPie uses the user input to draw the pie chart
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.
print() This method prints the contents that are displayed on the frame
printFrame() This method prints the contents that are displayed on the frame
SetFrameRef() Set the current value of the frame reference
setGraphicsVal() Set the current Graphic g value.
setHeight(int h) Set the height to 600 if h less than 0
setupButtons() The setupButtons() method allocates and sets up the JButtons.
  1. Declare the push buttons
  2. Set the background colors for the push buttons
  3. Add the buttons to the button panel
  4. Add event handlers to each button
setupPanels() The setupPanels() methos is used to create the JPanles used in this application/applet.
  1. Declare a JPanel - textPanel
  2. Set Layout Manager for textPanel to GridLayout
  3. Declare a JPanel - buttonPanel
  4. Declare a JPanel - myChart - area where pie chart or bar chart is rendered
setupText() The setupText() method allocates and sets up the entry text fields and labels used to gather user input.
  1. Declare a JLabel
  2. Declare 5 JTextFields
  3. Add the label to the text panel
  4. Add text fields to the text panel
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_III Final Product
PieChart_III Final Product
  
/**
 * File: PieBarGraph.java
 * This program takes user input and creates a pie and/or bar chart
 * Copyright (c) 2002-2009 Advanced Applications Total Applications Works.
 * (AATAW)  All Rights Reserved.
 ****************************************************************/




/** ***************************************************************
 *  class PieChart is used to create a simple pie chart based on
 *  user data input.
 **************************************************************** */
public class PieBarGraph extends JApplet implements ActionListener , Printable {
   
   /** ********************************************************
    * 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.
    *  1- Declare a JPanel - textPanel
    *  2- Set Layout Manager for textPanel to GridLayout
    *  3- Declare a JPanel - buttonPanel
    *  4- Declare a JPanel - myChart - area where pie chart 
    *     or bar chart is rendered
    *  
    ********************************************************/
   public void setupPanels() { 

   }

   /**  ****************************************************
    * The setupText() method allocates and sets up the entry
    * text fields used to gather user input.
    * 1- Declare a JLabel
    * 2- Declare 5 JTextFields
    * 3- Add the label to the text panel
    * 4- Add text fields to the text panel
    *  
    ********************************************************/
   public void setupText() { 

   }

   /**  ****************************************************
    * The setupButtons() method allocates and sets up the
    * JButtons.
    * 1- Declare the push buttons
    * 2- Set the background colors for the push buttons
    * 3- Add the buttons to the button panel
    * 4- Add event handlers to each button
    *  
    ********************************************************/
   public void setupButtons() { 

   }

   /**  ****************************************************
    * 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 ; }


   /** */
   public void setGraphicsVal( Graphics g )     {
      gVal = g;
   }

   /**
   public Graphics getGraphicsVal(  )      {
      return gVal ;
   }  */

   /**   ******************************************************
    * The checkFields() method ensures that the data is not null
    * 1- Obtain the data from each field
    * 2- Determine if any field is null
    * 3- Verify that each piece of data is a digit  
    * 
    ***********************************************************/
   public boolean checkFields( ) { 

   }

   /** ****************************************************
    * 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.
    * 1- Obtain each value in order
    * 2- Determine the length of each value in order 
    * 3- Parse is value a character at a time
    * 4- If value is not a digit, determine which field
    *    - return value indicating value is not a digit 
    * 5- Otherwise, indicate all values are digits
    * 
    ***************************************************** */
   public boolean  checkDigit( ) {

 
   }

   /** **************************************************
    *  The checkFieldsChange() method checks if data in
    *  the text fields has changed since the last check.
    ****************************************************/
   public void checkFieldsChange( ActionEvent e ) {


   }

   /**  **************************************************
    * The getTextValues() method retrieves data from the
    * text entry fields.
    ****************************************************/
   public void getTextValues() {

   }


   /** **************************************************
    *  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 )  {
 
   }

   /** ***********************************************************
    * 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) {

   }

   /** **************************************************
    * drawBar uses the user input to draw the bar chart
    ****************************************************/
   public void drawBar( Graphics g) {
 
   }

   /** *********************************************************
    * This method prints the contents that are displayed
    * on the frame
    ************************************************************/
   public void printFrame( Graphics g ) {


   }


   /** *********************************************************
    * This method prints the contents that are displayed
    * on the frame
    ************************************************************/
   public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
  
   }


   /** ****************************************************
    * sysPrint() is used to print out debugging messages.
    ***************************************************** */
   public void sysPrint( String 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[] )
   {
      
   }


   /** ********************************************************
    *  subclass of JPanel to allow drawing in a separate area
    ***********************************************************/
   public class ChartPanel extends JPanel  {
       

   }

   /** ******************************************************
       *  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 butChoice equals
       *
       *                   0- The pie chart button was pressed.
       *                   1- The bar chart button was pressed.
       *                   2- The print button was pressed.
       *                   3- The help button was pressed.
       *                   4- The about 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 )  {

 
   }
}



  

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 -

Printable - The Printable interface is implemented by the print methods of the current page painter, which is called by the printing system to render a page.

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 C#

© 2002 - 2016 All Rights Reserved Total Application Works