Link to home
Start Free TrialLog in
Avatar of CharleneS77
CharleneS77Flag for United States of America

asked on

How do I repaint a panel after using ActionListener?

I am attempting to repaint my coinsPanel after a button is pressed.  Can someone please take a look at this and let me know what I am missing?
// Coins enum
 
package project3;
 
import java.awt.*;
 
//******************************************************************************
// Coins enum
public enum Coins 
{		
	// types of coins ---> coin( color, size, denomination )
   QUARTER( Color.LIGHT_GRAY, 80, "25" ),
   DIME( Color.LIGHT_GRAY, 60, "10" ),
   NICKEL( Color.GRAY, 70, "5" ),
   PENNY( Color.YELLOW, 65, "1" );
   
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	// instance variables should always be declared private	
 	// coin characteristics
   private Color color;
   private int size;
   private String denomination;
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	
	//****************************************************************
	// Coins constructor	   
   private Coins( Color color, int size, String denomination )
   {
		this.color = color;
      this.size = size;
      this.denomination = denomination;
   }
	
	// declare all public methods before all private methods and
	// enumerate the methods in alphabetical order by name	
	//****************************************************************
	// the draw method is called by the paintComponent method		
	// the draw method has to have the Graphics object passed to it
	//     so it has something to draw on
	// the width and heigth do not need to be passed here because
	//     that depends upon the coin
	// the x and y coordinate parameters specify where to draw the coin
	public void draw( Graphics g, int X, int Y)
	{				
		color = this.getColor( );
		size = this.getSize( );
		denomination = this.getDenomination( );
			
		// draws three coin outlines to make a thicker outline
      g.drawOval( X, Y, size, size );				// draw coin outline
		g.drawOval( X, Y, size + 1, size + 1 );	// draw coin outline
		g.drawOval( X, Y, size + 2, size + 2 );	// draw coin outline
			
		// set coin color						
      g.setColor( color );	// coin color 
			
		// fill coin
      g.fillOval( X, Y, size, size ); // fill coin			
	}	
	
	//****************************************************************
	// the getColor method returns the color of the current coin
	//     in the foreach loop in the paintComponent method
   public Color getColor( )
   {
   	return color;
   }
 
	//****************************************************************
	// the getDenomination method returns the denomination of the 
	//     current coin in the foreach loop in the paintComponent method			
   public String getDenomination( )
   {
   	return denomination;
   }
 
	//****************************************************************
	// the getSize method returns the size of the current coin
	//     in the foreach loop	in the paintComponent method		
   public int getSize( )
   {
   	return size;
   }
		
	//****************************************************************	   
}// end Coins enum
 
 
//===================================================================
//===================================================================
 
 
// CoinsDrawingPanel class
 
package project3;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
//******************************************************************************
// CoinsDrawingPanel class
class CoinsDrawingPanel extends JPanel
{
	private static final int WINDOW_HEIGHT = 1000;
   private static final int WIDTH_OF_ONE_SIDE = 485;
   private static final int HEIGHT_OF_ONE_SIDE = 485;
      
   // constant colors
   Color TEXT_COLOR = Color.BLACK;
   Color COIN_OUTLINE_COLOR = Color.BLACK;
         
	// constants used for coin spacing
   private static final int SPACE_TO_COIN_TYPE = 90;      // x coordinate for every coin type
   private static final int COIN_OVERLAP = 30;                  // y coordinate for every coin type
         
   Coins coin;
   private Color coinColor;
	
		
	CoinsDrawingPanel coinsDrawingPanel;
	         
   // constants used for textAmountToDisplay spacing
   private static final int SPACE_TO_AMOUNT_TEXT_FROM_LEFT = 95;      // x coordinate 
   private static final int SPACE_TO_AMOUNT_TEXT_FROM_TOP = 950;      // y coordinate      
	
 
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	// instance variables should always be declared private	
   // instance variable used in paintComponent
	
	//private Coins coin;
   //private Color coinColor;
	
  	// the coinTypeCount array holds the coin types
   //			-position 0 is the number of quarters
   //			-position 1 is the number of dimes
	//			-position 2 is the number of nickels
	//			-position 3 is the number of pennies
   // 	-coinTypeCount SHOULD BE AN INSTANCE VARIABLE
	//private int [ ] coinTypeCount = new int[ Coins.values( ).length ];
   //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	
   //-----------------------------------------------------------------------------
	// constructor method
	public CoinsDrawingPanel( )     
   {
   	//setPreferredSize( new Dimension( WIDTH_OF_ONE_SIDE, HEIGHT_OF_ONE_SIDE ) );
   	setBackground( Color.YELLOW );
      //setVisible( true );
	}
      
   //-----------------------------------------------------------------------------
	// paintComponent method
   @Override public void paintComponent( Graphics g )       // @ = AT = Annotation Type
   {
   	super.paintComponent( g );  // Ask parent to paint background.
            
      // draw the coins
      int typeOfCoin = 0;
      int spaceToCoinType = 0;
      int denomination = 0;
     
	   WindowLayout2 localWindowLayout2 = new WindowLayout2( );
		int[ ] localCoinTypeCount = localWindowLayout2.getArray( );
 
      // display coins using icons 
		// for-each loop, for each possible coin
		// this for-each loop first
		// the values method returns an array of the enum values
		// the for-each loop is used to get the color, size, and denomination for QUARTER, 
		//	  and then all of the quarters are drawn using the inner for loop
		// then the for-each loop is used to get the color, size, and denomination for DIME,
		//   and then all of the dimes are drawn using the inner for loop
		// then the for-each loop is used to get the color, size, and denomination for NICKEL, 
		//   and then all of the nickels are drawn using the inner for loop 
		// then the for-each loop is used to get the color, size, and denomination for PENNY, 
		//   and then all of the pennies are drawn using the inner for loop      
      for (Coins coins: Coins.values())
      {                                       
         coinColor = coins.getColor( );                     // invokes getColor of current coin type
         int coinSize = coins.getSize( );                   // invokes getSize of current coin type
         String coinDenomination = coins.getDenomination( );// invokes getDenomination of current coin type
			
                                                                          
         // the coinNumber integer is the loop control variable that varifies
         //                  from 0 to one less than the number of coins.  It is used to
         //                  compute the y coordinate of each successive coin.                        
         for (int coinNumber = 0; coinNumber < localCoinTypeCount[ typeOfCoin ]; coinNumber++)
         {
         	g.setColor( COIN_OUTLINE_COLOR );
                  
            // Notice that if you pass the position of where to draw each coin, 
            //    you can greatly simplify the code. Notice too that I do not pass 
            //    the coin type but the coin is the object on which the method is 
            //    invoked.                        
            coins.draw( g , (typeOfCoin + 1) * SPACE_TO_COIN_TYPE, 
                                                (coinNumber + 1)* COIN_OVERLAP);
                                                                  
            g.setColor( TEXT_COLOR );      // text color (black)
            g.drawString( coinDenomination, ( SPACE_TO_COIN_TYPE * ( typeOfCoin + 1 ) ) + ( ( coinSize - 8 ) / 2 ) ,
                                    ( COIN_OVERLAP + ( ( coinSize + 8 ) / 2 ) ) + ( COIN_OVERLAP * coinNumber ) );  
						                     
         }                      
         typeOfCoin++;
			
			//////////////////////////////////////////////////////////
			g.fillOval( 25, 25, 50, 50 ); ////////////////// test oval
			//////////////////////////////////////////////////////////
      }                                                          
   }
   
	//-----------------------------------------------------------------------------      
	// getMinimumSize method
   public Dimension getMinimumSize( )
   {
         return getPreferredSize( );
   }
      
   //----------------------------------------------------------------------------- 
	// getPreferredSize method
   public Dimension getPreferredSize( )
   {
         return new Dimension( WIDTH_OF_ONE_SIDE, WINDOW_HEIGHT / 2 );
   }
      
   //-----------------------------------------------------------------------------      
} // end CoinsDrawingPanel class
 
 
//===================================================================
//===================================================================
 
 
// MeterDrawingPanel class
 
package project3;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
//******************************************************************************
// MeterDrawingPanel class
class MeterDrawingPanel extends JPanel 
{
	private static final int WINDOW_HEIGHT = 1000;
   private static final int SIDE_WIDTH = 485;
   private static final int SIDE_HEIGHT = 485;
      
   // constants used for drawing the parking meter
   private static final int X_TOP_CORNER_RECTANG_FOR_ARC = 92;
   private static final int Y_TOP_CORNER_RECTANG_FOR_ARC = 175;
   private static final int SIZE_OF_ARC = 300;
   private static final int ARC_BEGINNING_DEGREE = 0;
   private static final int ARC_ENDING_DEGREE = 180;
   private static final int X_BEGIN_OF_METER_BOTTOM = 92;
   private static final int Y_BEGIN_OF_METER_BOTTOM = 325;
   private static final int X_END_OF_METER_BOTTOM = 392;
   private static final int Y_END_OF_METER_BOTTOM = 325;
   private static final int X_NEEDLE_ATTACHMENT = 237;
   private static final int Y_NEEDLE_ATTACHMENT = 320;
   private static final int NEEDLE_ATTACHMENT_SIZE = 10;
   private static final int X_ORIGIN = 242;      // x center of arc
   private static final int Y_ORIGIN = 325;      // y center of arc
   private static final int RADIUS = 150;      // length of meter needle
      
   //-----------------------------------------------------------------------------
 
   public MeterDrawingPanel( )      // constructor
   {
   	//setPreferredSize( new Dimension( WIDTH_OF_ONE_SIDE, HEIGHT_OF_ONE_SIDE ) );
      setBackground( Color.ORANGE );
      //setVisible( true );
	}
      
   //-----------------------------------------------------------------------------
	// paintComponent method
   @Override public void paintComponent( Graphics g )       // @ = AT = Annotation Type
   {
   	super.paintComponent( g );  // Ask parent to paint background.
 
      // draw the analog parking meter
		g.setColor( Color.BLACK );
		
		// arc of meter		          
      g.drawArc( X_TOP_CORNER_RECTANG_FOR_ARC, Y_TOP_CORNER_RECTANG_FOR_ARC, SIZE_OF_ARC, 
                                    SIZE_OF_ARC, ARC_BEGINNING_DEGREE, ARC_ENDING_DEGREE ); 
		// bottom of meter
      g.drawLine( X_BEGIN_OF_METER_BOTTOM, Y_BEGIN_OF_METER_BOTTOM, 
                                    X_END_OF_METER_BOTTOM, Y_END_OF_METER_BOTTOM );      
		// small circle where meter needle will be attached
      g.fillOval( X_NEEDLE_ATTACHMENT, Y_NEEDLE_ATTACHMENT, 
                                    NEEDLE_ATTACHMENT_SIZE, NEEDLE_ATTACHMENT_SIZE ); 
		// new font											                                          
      Font font = new Font( "Aerial", Font.PLAIN, 11 ); 
      g.setFont( font );       // set font
                  
      //Percentage is a value between 0 and 1. If zero, the needle will point to the
      //   left, if one it will point to the right. If it's 0.5 it will point upwards.
      double percentage = 0.0;
      int xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      int yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "0 Min", X_ORIGIN + xPercentage - 25, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------            
      percentage = .125;
      xPercentage = 
                        ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = 
                        ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "15 Min", X_ORIGIN + xPercentage - 30, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------            
      percentage = .25;
      xPercentage = 
                        ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = 
                        ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "30 Min", X_ORIGIN + xPercentage - 30, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
		//-----------------            
      percentage = .375;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "45 Min", X_ORIGIN + xPercentage - 25, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number        
      //-----------------            
      percentage = .50;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle      
      g.setColor( Color.BLACK );
      g.drawString( "60 Min", X_ORIGIN + xPercentage - 15, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------          
      percentage = .625;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "75 Min", X_ORIGIN + xPercentage + 5, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------                             
      percentage = .75;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle      
      g.setColor( Color.BLACK );
      g.drawString( "90 Min", X_ORIGIN + xPercentage + 5, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------          
      percentage = .875;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );
      g.drawString( "105 Min", X_ORIGIN + xPercentage + 5, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number
      //-----------------           
      percentage = 1.0;
      xPercentage = ( int ) Math.round( Math.sin( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      yPercentage = ( int ) Math.round( Math.cos( ( - percentage - 0.5 ) * Math.PI ) * RADIUS );
      g.setColor( Color.LIGHT_GRAY );
      g.drawLine( X_ORIGIN, Y_ORIGIN, X_ORIGIN + xPercentage, 
                                    Y_ORIGIN + yPercentage );      // meter needle
      g.setColor( Color.BLACK );      
      g.drawString( "120 Min", X_ORIGIN + xPercentage + 5, 
                                    Y_ORIGIN + yPercentage - 5 );  // meter number                                                
	}
     
   //-----------------------------------------------------------------------------
	// getMinimumSize method
	public Dimension getMinimumSize( )
   {
   	return getPreferredSize( );
   }
      
   //-----------------------------------------------------------------------------  
	// getPreferredSize method 
   public Dimension getPreferredSize( )
   {
   	return new Dimension( SIDE_WIDTH, WINDOW_HEIGHT / 2 );
   }
      
   //-----------------------------------------------------------------------------      
}// end MeterDrawingPanel class
 
 
//===================================================================
//===================================================================
 
// WindowsLayout3 class
 
package project3;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
//******************************************************************************
// WindowLayout3 class
class WindowLayout3 extends JFrame implements ActionListener
{
	//#################################################
   private static final int WINDOW_WIDTH = 925;
   private static final int WINDOW_HEIGHT = 925;
   private static final int SIDE_WIDTH = 450;		
   private static final int SIDE_HEIGHT = 925;	
   private static final int BUTTON_PANEL_HEIGHT = 30;
   private static final int FONT_SIZE = 18;
	//#################################################
	    
	/*
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	// instance variables should always be declared private	
   // instance variable used in paintComponent
	
	//private Coins coin;
   private Color coinColor;
	
  	// the coinTypeCount array holds the coin types
   //			-position 0 is the number of quarters
   //			-position 1 is the number of dimes
	//			-position 2 is the number of nickels
	//			-position 3 is the number of pennies
   // 	-coinTypeCount SHOULD BE AN INSTANCE VARIABLE
	private int [ ] coinTypeCount = new int[ Coins.values( ).length ];      
	*/   
	    
   //private JFrame ParkingMeter = new JFrame( "Parking Meter" );
      
   private int [ ] coinTypeCount;   
   
   private int numberOfQuarters = 0;
   private int numberOfDimes = 0;
   private int numberOfNickels = 0;
   private int numberOfPennies = 0;
	
	// instance variable used in setAmountString method
	private int userAmount = 0;
      
   //---------coins---------------------
   // coins JPanels
   private JPanel coinsPanel;
   private JPanel coinsButtonPanel;
   private CoinsDrawingPanel paintedCoins = new CoinsDrawingPanel( );
      
   // coins JLabel
   private JLabel coinsAmountLabel;
   private String coinsAmount = "Waiting for coins...";
		
   // coins buttons
   private JButton quarterButton;
   private JButton dimeButton;
   private JButton nickelButton;
   private JButton pennyButton;
    
   //---------meter---------------------
   //meter JPanels
   private JPanel meterPanel;
   private MeterDrawingPanel paintedMeter = new MeterDrawingPanel( );
 
   // meter JLabel
   private JLabel meterAmountLabel;     
   private String meterAmount = "Waiting for coins...";
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   
	  	
   //----------------------------------------------------------------------------- 
	// constructor method
   public WindowLayout3( )      
   {
   	super( "Parking Meter" );
		//coinsPanel.setBackground( Color.WHITE );
      initialize( );
   }
      
	//-----------------------------------------------------------------------------
	// actionPerformed method
	public void actionPerformed( ActionEvent event )
	{
	
		/*
		if( userAmount == 99 )
		{
			JOptionPane dialog = new JOptionPane();
			dialog.showMessageDialog( null, "This is an error, try again", "Error",
														JOptionPane.ERROR_MESSAGE );
				
			return;
		}
		*/
		
		if( event.getSource( ) == quarterButton )
		{
			if( numberOfQuarters == 3 )
			{
				// cannot have more than 3 quarters
				// repaint( );
				// return;
			}
			else
			{
				numberOfQuarters++;	// add one quarter to numberOfQuarters
				coinTypeCount[ 0 ] = numberOfQuarters;	// store numberOfQuarters in position 0
				// coinTypeCount[ 0 ]++;
				userAmount += 25;
				setAmountString( userAmount );
				repaint( );
			}
		}
		else if( event.getSource( ) == dimeButton )
		{
			if( numberOfDimes == 2 )
			{
				// cannot have more than 2 dimes
				// repaint( );
				// return;
			}
			else
			{
				numberOfDimes++;	// add one dime to numberOfDimes
				coinTypeCount[ 1 ] = numberOfDimes;	// store numberOfDimes in position 1
				// coinTypeCount[ 1 ]++;
				userAmount += 10;
				setAmountString( userAmount );
				repaint( );
			}
		}
		else if( event.getSource( ) == nickelButton )
		{
			if( numberOfNickels == 1 )
			{
				// cannot have more than 1 nickel
				// repaint( );
				// return;
			}
			else
			{
				numberOfNickels++;	// add one nickel to numberOfNickels
				coinTypeCount[ 2 ] = numberOfNickels;	// store numberOfNickels in position 2
				// coinTypeCount[ 2 ]++;
				userAmount += 5;
				setAmountString( userAmount );
				repaint( );
			}
		}
		else if( event.getSource( ) == pennyButton )
		{
			if( numberOfPennies == 4 )
			{
				// cannot have more than 4 pennies
				// repaint( );
				// return;
			}
			else
			{
				numberOfPennies++;	// add one penny to numberOfPennies
				coinTypeCount[ 3 ] = numberOfPennies;	// store numberOfPennies in position 3
				// coinTypeCount[ 3 ]++;
				userAmount += 1;
				setAmountString( userAmount );
				repaint( );
			}
		}
		
		// sum total amount of all coins (or sum total as I go)
		
		// pass total amount of all coins to setAmountString method
		// decide the proper time to call setAmountString
		//setAmountString( userAmount );
		
	}// end actionPerformed
	
	//-----------------------------------------------------------------------------
	// getArray method
   public int[ ] getArray( )
	{
		return( coinTypeCount );
	} // end getArray	
	
   //-----------------------------------------------------------------------------
	// initialize method
   public void initialize( )            
   {
		coinTypeCount = new int[ Coins.values( ).length ]; 
		
      // setup myContainer
      Container myContainer = getContentPane( );
      myContainer.setBackground( Color.RED );
      setLayout( new BorderLayout( ) );
      setSize( WINDOW_WIDTH, WINDOW_HEIGHT );		
   
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
		// setup coinsPanel
      coinsPanel = new JPanel( );
      coinsPanel.setPreferredSize( new Dimension( SIDE_WIDTH, SIDE_HEIGHT ) );
 		coinsPanel.setLayout( new FlowLayout( ) );
		coinsPanel.setBackground( Color.BLUE );				// Color.BLUE		
		//	The coinsPanel background is blue, but it is covered by other panels 
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      
      // setup coinsButtonPanel
      coinsButtonPanel = new JPanel( );
      //coinsButtonPanel.setPreferredSize( new Dimension( SIDE_WIDTH, BUTTON_PANEL_HEIGHT ) );
		coinsButtonPanel.setPreferredSize( new Dimension( SIDE_WIDTH * 2, BUTTON_PANEL_HEIGHT * 2 ) );
      coinsButtonPanel.setLayout( new GridLayout( 1, 4 ) );
		coinsButtonPanel.setBackground( Color.ORANGE );  	// Color.ORANGE
		// The coinsButtonPanel is orange, but the buttons cover the whole panel   
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~           
      // setup quarterButton
      quarterButton = new JButton( "25¢" );
      quarterButton.setFont( new Font( "Arial", Font.PLAIN, FONT_SIZE ) );
		quarterButton.setForeground( Color.BLACK );
      quarterButton.setBackground( Color.LIGHT_GRAY );
      quarterButton.setEnabled( true );
      quarterButton.addActionListener( this );							            
      // setup dimeButton
      dimeButton = new JButton( "10¢" );
      dimeButton.setFont( new Font( "Arial", Font.PLAIN, FONT_SIZE ) );
      dimeButton.setForeground( Color.BLACK );
      dimeButton.setBackground( Color.LIGHT_GRAY );
      dimeButton.setEnabled( true );
		dimeButton.addActionListener( this );				
      // setup nickelButton
      nickelButton = new JButton( "5¢" );
      nickelButton.setFont( new Font( "Arial", Font.PLAIN, FONT_SIZE ) );
      nickelButton.setForeground( Color.BLACK );
      nickelButton.setBackground( Color.LIGHT_GRAY );
      nickelButton.setEnabled( true );
      nickelButton.addActionListener( this );						
      // setup pennyButton
      pennyButton = new JButton( "1¢" );
      pennyButton.setFont( new Font( "Arial", Font.PLAIN, FONT_SIZE ) );
      pennyButton.setForeground( Color.BLACK );
      pennyButton.setBackground( Color.LIGHT_GRAY );
      pennyButton.setEnabled( true );
      pennyButton.addActionListener( this );
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~             
      // setup coinsAmountLabel
      coinsAmountLabel = new JLabel( coinsAmount, SwingConstants.LEFT );
		coinsAmountLabel.setPreferredSize(new Dimension( SIDE_WIDTH, WINDOW_HEIGHT / 2 ));
      coinsAmountLabel.setFont( new Font( "Monospaced", Font.BOLD, FONT_SIZE ) );
		coinsAmountLabel.setOpaque( true );		//required to set background color
		coinsAmountLabel.setBackground( Color.BLACK );
      coinsAmountLabel.setForeground( Color.GREEN );
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                   
      // add coin buttons to coinsButtonPanel
      coinsButtonPanel.add( quarterButton );
      coinsButtonPanel.add( dimeButton );
      coinsButtonPanel.add( nickelButton );
      coinsButtonPanel.add( pennyButton );
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       
      // add coinsButtonPanel, paintedCoins (coinsDrawingPanel), and coinsAmountLabel to coinsPanel
      coinsPanel.setLayout( new BorderLayout( ) );
      coinsPanel.add( coinsButtonPanel, BorderLayout.NORTH );
      coinsPanel.add( paintedCoins, BorderLayout.CENTER );
      coinsPanel.add( coinsAmountLabel, BorderLayout.SOUTH );      
		
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~           
      // setup meterPanel
      meterPanel = new JPanel( );
      meterPanel.setLayout( new BorderLayout( ) );
      meterPanel.setPreferredSize( new Dimension( SIDE_WIDTH, WINDOW_HEIGHT ) );
      meterPanel.setBackground( Color.YELLOW );            
		//	The meterPanel background is yellow, but it is covered by other panels 
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~		            
      // setup meterAmountLabel
      meterAmountLabel = new JLabel( meterAmount, SwingConstants.LEFT );
		meterAmountLabel.setPreferredSize(new Dimension( SIDE_WIDTH, WINDOW_HEIGHT / 2 ));
      meterAmountLabel.setFont( new Font( "Monospaced", Font.BOLD, FONT_SIZE ) );
	   meterAmountLabel.setOpaque( true );		//required to set background color
		meterAmountLabel.setBackground( Color.GREEN );
      meterAmountLabel.setForeground( Color.BLACK );
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~		            
      // add paintedMeter (meterDrawingPanel) and meterAmountLabel to meterPanel
      meterPanel.setLayout( new BorderLayout( ) );
      meterPanel.add( paintedMeter, BorderLayout.NORTH );
      meterPanel.add( meterAmountLabel, BorderLayout.CENTER );
		
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||		
      // add coinsPanel and meterPanel to myContainer
      add( coinsPanel, BorderLayout.WEST );
      add( meterPanel, BorderLayout.EAST );		
      //|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~				  
	} // end initialize method
      
   //-----------------------------------------------------------------------------  
	// getMinimumSize method
   public Dimension getMinimumSize( )
   {
		return getPreferredSize( );
   }
      
   //-----------------------------------------------------------------------------
	// getPreferredSize method
   public Dimension getPreferredSize( )
   {
   	return new Dimension( WINDOW_WIDTH, WINDOW_HEIGHT );
   }
      
   //-----------------------------------------------------------------------------  
	// paintComponent method 
   public void paintComponent( Graphics g )       
   {
   	//super.paintComponent( g );  // Ask parent to paint background.
      paintComponent( g );    
      //coinsPanel.repaint( );
	}
      
   //-----------------------------------------------------------------------------   
	// main method 
   public static void main( String [ ] args )
   {
   	WindowLayout3 windowLayout3 = new WindowLayout3( );
      windowLayout3.setVisible( true );
      windowLayout3.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		//windowLayout3.repaint( );
	}// end main method  
	
   //****************************************************************
   // setAmountString method determines the amount in words
   public void setAmountString( int someAmount ) // this method is called by setChange method
	{
		// the setAmountString method cannot access the Graphics object
		// the setAmountString method cannot paint anything
		// the setAmountString method just determines the words
		//     and leaves them behind in an instance variable
		//	    for the paintComponent method
        						
      userAmount = someAmount;
      
     	// display coins using icons together with text indicating 
     	// the amount entered expressed in words
  	   //----------------------------------------------------------
		// class invariant:  the amount displayed in painted coins
		//							is always equal to the text amount 
		//							displayed below them
		//----------------------------------------------------------
         
      String[ ] textAmount = { "Zero", "One", "Two", "Three", "Four", "Five", 
               					 "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", 
               					 "Twelve", "Thirteen", "Fourteen", "Fifteen",
               					 "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
										 								 	
		if( userAmount < 1 )
      {     	
      	coinsAmount = "* Error occurred...amount is less than 1 *";
      }	
      else if( userAmount > 0 && userAmount < 20 )
      {
      	coinsAmount = textAmount[ userAmount ] + " Cent(s)";
      }  
      else if( userAmount > 19 && userAmount < 30 )
      {
         coinsAmount = "Twenty  " + textAmount[ userAmount - 20 ] + " Cents";
      }   
      else if( userAmount > 29 && userAmount < 40 )
      {
         coinsAmount = "Thirty  " + textAmount[ userAmount - 30 ] + " Cents";
      }   
      else if( userAmount > 39 && userAmount < 50 )
      {
         coinsAmount = "Forty  " + textAmount[ userAmount - 40 ] + " Cents";
      }   
      else if( userAmount > 49 && userAmount < 60 )
      {
         coinsAmount = "Fifty  " + textAmount[ userAmount - 50 ] + " Cents";
      }   
      else if( userAmount > 59 && userAmount < 70 )
      {
         coinsAmount = "Sixty  " + textAmount[ userAmount - 60 ] + " Cents";
      }  
      else if( userAmount > 69 && userAmount < 80 )
      {
         coinsAmount = "Seventy  " + textAmount[ userAmount - 70 ] + " Cents";
      }  
      else if( userAmount > 79 && userAmount < 90 )
      {
         coinsAmount = "Eighty  " + textAmount[ userAmount - 80 ] + " Cents";
      }   
      else if( userAmount > 89 && userAmount < 100 )
      {
         coinsAmount = "Ninety  " + textAmount[ userAmount - 90 ] + " Cents";
      }
      else if( userAmount > 99 )
      {
         coinsAmount = "* Error occurred...amount is greater than 99 *";	
      }
				
   } // end setAmountString method            
}// end WindowLayout3 class
 
 
//===================================================================
//===================================================================

Open in new window

SOLUTION
Avatar of sciuriware
sciuriware

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CEHJ
Do i take it that you've been given code and asked to add functionality to it? If so, what is your assignment spec?
Avatar of CharleneS77

ASKER

With some assistance, I have written all of the code.  This program should paint coins in the coins panel and display the amount (in text) below the coins.  The meter should display how much time is remaining depending on the amount of coins.
Well that's quite impressive. Unfortunately there's no code (that i can see) to increment the meter needle
I have not yet written the code to calculate where to put the needle.  I am working on the buttons right now.  Once I get my buttons working (and my coins are being painted), I will add the meter needle.  I just can't figure out how to get a coin painted each time a button is pressed.
You need to keep a list of coins and iterate them, painting them and offsetting them slightly on each iteration
List<List<Coins>> is the container you need. I think your enum should be called Coin btw
I was able to paint the coins for my last project.  If it helps anything, I am including my last project.  You can run this to see the end result.  The current project is similar, except I am adding the meter.  I cannot figure out what I am missing to get the buttons to work.

// Coins enum
 
package project2;
 
import java.awt.*;
//import javax.swing.*;
 
 
public enum Coins 
{		
	// types of coins ---> coin( color, size, denomination )
   QUARTER( Color.LIGHT_GRAY, 80, "25" ),
   DIME( Color.LIGHT_GRAY, 60, "10" ),
   NICKEL( Color.GRAY, 70, "5" ),
   PENNY( Color.YELLOW, 65, "1" );
   
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	// instance variables should always be declared private	
 	// coin characteristics
   private Color color;
   private int size;
   private String denomination;
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	
	//****************************************************************
	// Coins constructor	   
   private Coins( Color color, int size, String denomination )
   {
		this.color = color;
      this.size = size;
      this.denomination = denomination;
   }
	
	// declare all public methods before all private methods and
	// enumerate the methods in alphabetical order by name	
	//****************************************************************
	// the draw method is called by the paintComponent method		
	// the draw method has to have the Graphics object passed to it
	//     so it has something to draw on
	// the width and heigth do not need to be passed here because
	//     that depends upon the coin
	// the x and y coordinate parameters specify where to draw the coin
	public void draw( Graphics g, int X, int Y)
	{				
		color = this.getColor( );
		size = this.getSize( );
		denomination = this.getDenomination( );
			
		// draws three coin outlines to make a thicker outline
      g.drawOval( X, Y, size, size );				// draw coin outline
		g.drawOval( X, Y, size + 1, size + 1 );	// draw coin outline
		g.drawOval( X, Y, size + 2, size + 2 );	// draw coin outline
			
		// set coin color						
      g.setColor( color );	// coin color 
			
		// fill coin
      g.fillOval( X, Y, size, size ); // fill coin			
	}	
	
	//****************************************************************
	// the getColor method returns the color of the current coin
	//     in the foreach loop in the paintComponent method
   public Color getColor( )
   {
   	return color;
   }
 
	//****************************************************************
	// the getDenomination method returns the denomination of the 
	//     current coin in the foreach loop in the paintComponent method			
   public String getDenomination( )
   {
   	return denomination;
   }
 
	//****************************************************************
	// the getSize method returns the size of the current coin
	//     in the foreach loop	in the paintComponent method		
   public int getSize( )
   {
   	return size;
   }
		
	//****************************************************************	   
}// end Coins enum
 
 
//============================================
//============================================
 
// GraphicsWindow class
 
package project2;
 
import java.awt.*;
import javax.swing.*;
 
 
public class GraphicsWindow extends JPanel
{
	private JFrame window;
   
	public GraphicsWindow( String windowName, int width, int height )
   {  
   	window = new JFrame( windowName );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setBackground( Color.WHITE );
      window.getContentPane( ).add( this );
      window.setSize( width, height ); 
   }
   
	public int display( )
   {
      
  		window.setVisible( true );
      return 0;
      
   }
} // end GraphicsWindow class
 
 
//============================================
//============================================
 
 
// ChangeWindow class
 
package project2;
 
import java.awt.*;
//import javax.swing.*;
 
 
// public classes can be accessed from other packages
public class ChangeWindow extends GraphicsWindow 	// uses GraphicsWindow class to create window
{	
//----------------------------------------------------------
// --->  includes comments describing class invariants  <---
// 	An invariant is a condition that must remain true
//		throughout the life of the objects of a class.
//----------------------------------------------------------
   
	//################################################################
	// instance constants
	// constant window size
   private static final int WINDOW_WIDTH = 495;
   private static final int WINDOW_HEIGHT = 300; 
   
  	// constant colors
   Color TEXT_COLOR = Color.BLACK;
   Color COIN_OUTLINE_COLOR = Color.BLACK;
   	
  	// constants used for coin spacing
   // the SPACE_TO_COIN_TYPE constant represents the X coordinate for 
   //			the coin type
   // the COIN_OVERLAP constant represents the Y coordinate for every 
   //			coin type
   private static final int SPACE_TO_COIN_TYPE = 90;	// X coordinate
   private static final int COIN_OVERLAP = 20;			// Y coordinate
   	
  	// constants used for textAmountToDisplay spacing
   private static final int SPACE_TO_AMOUNT_TEXT_FROM_LEFT = 95;	// X coordinate
   private static final int SPACE_TO_AMOUNT_TEXT_FROM_TOP = 220;	// Y coordinate	
  	//################################################################
	
	
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	// instance variables should always be declared private	
   // instance variable used in paintComponent
	
	//private Coins coin;
   private Color coinColor;
	
  	// the coinTypeCount array holds the coin types
   //			-position 0 is the number of quarters
   //			-position 1 is the number of dimes
	//			-position 2 is the number of nickels
	//			-position 3 is the number of pennies
   // 	-coinTypeCount SHOULD BE AN INSTANCE VARIABLE
	private int [ ] coinTypeCount = new int[ Coins.values( ).length ];
   
 	// instance variables used in setChange method
   private int currentAmount;
   	
   private int remainderAfterQuarters = 0;
   private int amountInQuarters = 0;
   private int numberOfQuarters = 0;
   	
   private int remainderAfterDimes = 0;
   private int amountInDimes = 0;
   private int numberOfDimes = 0;
   	
   private int remainderAfterNickels = 0;
   private int amountInNickels = 0;
   private int numberOfNickels = 0;
   	
   private int remainderAfterPennies = 0;
   private int amountInPennies = 0;
   private int numberOfPennies = 0;
   
	// instance variables used in setAmountString method   
   private String textAmountToDisplay = "Waiting for amount...";
   private int userAmount;	   
   //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	
	
	// declare all public methods before all private methods and
	// enumerate the methods in alphabetical order by name
	//****************************************************************		
   // ChangeWindow constructor method
   public ChangeWindow( )
   {
		// call GraphicsWindow constructor (extends GraphicsWindow)
   	super( "Change Window", WINDOW_WIDTH, WINDOW_HEIGHT );	
   } // end ChangeWindow constructor method
	
	
   //****************************************************************
   // paintComponent method paints the window
	// paintComponent method is automatically called when ChangeWindow is instantiated in main
	// paintComponent method is called everytime repaint is called
   public void paintComponent( Graphics g )
   {			  
		// local variables
      // the typeOfCoin integer represents the type of coin:
      //			0 = quarters, 1 = dimes, 2 = nickels, 3 = pennies
      //	the typeOfCoin integer gets incremented after the number of
      //			coins for each coin type have been drawn
      // the typeOfCoin integer is the index of the coinTypeCount array
      int typeOfCoin = 0;	
			
      super.paintComponent( g ); 
      		
      setBackground( new Color( 0, 120, 0 ) );	// setBackground( Color.GREEN );
      
      Font font = new Font( "Aerial", Font.BOLD, 12 );  // new font
      g.setFont( font ); 	// set font						
      
      // display coins using icons 
		// for-each loop, for each possible coin
		// this for-each loop first
		// the values method returns an array of the enum values
		// the for-each loop is used to get the color, size, and denomination for QUARTER, 
		//	  and then all of the quarters are drawn using the inner for loop
		// then the for-each loop is used to get the color, size, and denomination for DIME,
		//   and then all of the dimes are drawn using the inner for loop
		// then the for-each loop is used to get the color, size, and denomination for NICKEL, 
		//   and then all of the nickels are drawn using the inner for loop 
		// then the for-each loop is used to get the color, size, and denomination for PENNY, 
		//   and then all of the pennies are drawn using the inner for loop
      for (Coins coins: Coins.values())	
      {		
			//----------------------------------------------------------
			// class invariant:  the coin color for quarters and dimes
			//							is always light_gray, for nickels is
			//							always gray, for pennies is always yellow.
			//							the denomination for quarters is always
			//							25, for dimes is 10, for nickels is 5, 
			// 						and for pennies is 1.
			//							the size for quarters is always 80, for
			//							dimes is 60, for nickels is 70, and for
			//							pennies is 65.
			//----------------------------------------------------------					
         coinColor = coins.getColor( );							// invoke getColor for current coin type
         int coinSize = coins.getSize( );						 	// invoke getSize for current coin type
         String coinDenomination = coins.getDenomination( );// invoke getDenomination for current coin type
      				
        	// the coinNumber integer is the loop control variable that verifies
        	//			from 0 to one less than the number of coins 
			// the coinNumber integer is used to compute the y coordinate of each
        	//		   successive coin.				
			for (int coinNumber = 0; coinNumber < coinTypeCount[ typeOfCoin ]; coinNumber++)
         {
         	g.setColor( COIN_OUTLINE_COLOR );
            	
          	//	the code is simplified by passing the position of where 
				//     to draw each coin 
           	// the coin type is not passed
				//	the coin is the object on which the method is invoked	
				// call draw method of the Coins enum, passing (graphicsObject, xCoordinate, yCoordinate)			
            coins.draw( g, (typeOfCoin + 1) * SPACE_TO_COIN_TYPE, 
                  								(coinNumber + 1)* COIN_OVERLAP);
            									
				//----------------------------------------------------------
				// class invariant:  the text amount displayed on each coin
				//							is always displayed with black text
				//----------------------------------------------------------
				g.setColor( TEXT_COLOR );	// text color (black)
				
				// draw coin amount on current coin
            g.drawString( coinDenomination, 
				  ( SPACE_TO_COIN_TYPE * ( typeOfCoin + 1 ) ) + ( ( coinSize - 8 ) / 2 ),
                ( COIN_OVERLAP + ( ( coinSize + 8 ) / 2 ) ) + ( COIN_OVERLAP * coinNumber ) ); 			
 			}
         typeOfCoin++;
  		}
      
		//	display text indicating the amount entered expressed in words 		
		//----------------------------------------------------------
		// class invariant:  the amount of displayed painted coins
		//							is always equal to the text amount 
		//							displayed below them
		//----------------------------------------------------------
		//----------------------------------------------------------
		// class invariant:  the text amount displayed below the coins
		//							is always displayed with black text
		//----------------------------------------------------------
      g.setColor( TEXT_COLOR );	// text color (black)
      font = new Font( "Aerial", Font.BOLD, 16 );  // new font
      g.setFont( font ); 	// set font
		
		// display amount in words
      g.drawString( textAmountToDisplay, 
               		SPACE_TO_AMOUNT_TEXT_FROM_LEFT, 
							  SPACE_TO_AMOUNT_TEXT_FROM_TOP );	    								
	} // end paintComponent method
	
		
   //****************************************************************
   // setAmountString method determines the amount in words
   public void setAmountString( int someAmount ) // this method is called by setChange method
	{
		// the setAmountString method cannot access the Graphics object
		// the setAmountString method cannot paint anything
		// the setAmountString method just determines the words
		//     and leaves them behind in an instance variable
		//	    for the paintComponent method
        						
      userAmount = someAmount;
      
     	// display coins using icons together with text indicating 
     	// the amount entered expressed in words
  	   //----------------------------------------------------------
		// class invariant:  the amount displayed in painted coins
		//							is always equal to the text amount 
		//							displayed below them
		//----------------------------------------------------------
         
      String[ ] textAmount = { "Zero", "One", "Two", "Three", "Four", "Five", 
               					 "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", 
               					 "Twelve", "Thirteen", "Fourteen", "Fifteen",
               					 "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
      								 	
		if( userAmount < 1 )
      {     	
      	textAmountToDisplay = "* Error occurred...amount is less than 1 *";
      }	
      else if( userAmount > 0 && userAmount < 20 )
      {
      	textAmountToDisplay = textAmount[ userAmount ] + " Cent(s)";
      }  
      else if( userAmount > 19 && userAmount < 30 )
      {
         textAmountToDisplay = "Twenty  " + textAmount[ userAmount - 20 ] + " Cents";
      }   
      else if( userAmount > 29 && userAmount < 40 )
      {
         textAmountToDisplay = "Thirty  " + textAmount[ userAmount - 30 ] + " Cents";
      }   
      else if( userAmount > 39 && userAmount < 50 )
      {
         textAmountToDisplay = "Forty  " + textAmount[ userAmount - 40 ] + " Cents";
      }   
      else if( userAmount > 49 && userAmount < 60 )
      {
         textAmountToDisplay = "Fifty  " + textAmount[ userAmount - 50 ] + " Cents";
      }   
      else if( userAmount > 59 && userAmount < 70 )
      {
         textAmountToDisplay = "Sixty  " + textAmount[ userAmount - 60 ] + " Cents";
      }  
      else if( userAmount > 69 && userAmount < 80 )
      {
         textAmountToDisplay = "Seventy  " + textAmount[ userAmount - 70 ] + " Cents";
      }  
      else if( userAmount > 79 && userAmount < 90 )
      {
         textAmountToDisplay = "Eighty  " + textAmount[ userAmount - 80 ] + " Cents";
      }   
      else if( userAmount > 89 && userAmount < 100 )
      {
         textAmountToDisplay = "Ninety  " + textAmount[ userAmount - 90 ] + " Cents";
      }
      else if( userAmount > 99 )
      {
         textAmountToDisplay = "* Error occurred...amount is greater than 99 *";	
      }
   } // end setAmountString method    
	
	  
   //****************************************************************	
   // setChange method allows the amount of change to be set, computes 
   //     and saves the number of each coin
   // calculates the fewest coins required for the amount entered 
   //     (between 1 and 99 cents)
	public void setChange( int someAmount )	// this method is called by main
   {
		// the setChange method cannot access the Graphics object
		// the setChange method cannot paint anything
		// the setChange method just determines the number
		//		 of coins and leaves them behind in instance variables 
		//	    for the paintComponent method
		
      currentAmount = someAmount;
      	
		remainderAfterQuarters = currentAmount % 25;	// calculate remainder after even division
      amountInQuarters = currentAmount - remainderAfterQuarters;	// amount in quarters
      numberOfQuarters = amountInQuarters / 25;	// number of quarters
      coinTypeCount[ 0 ] = numberOfQuarters;		// assign number of quarters to index 0
      currentAmount = currentAmount - amountInQuarters;	// remaining amount, used to calculate dimes
      
      remainderAfterDimes = currentAmount % 10;	// calculate remainder after even division
      amountInDimes = currentAmount - remainderAfterDimes;	// amount in dimes
      numberOfDimes = amountInDimes / 10;			// number of dimes
      coinTypeCount[ 1 ] = numberOfDimes;			// assign number of dimes to index 1
      currentAmount = currentAmount - amountInDimes;	// remaing amount, used to calculate nickels
      
      remainderAfterNickels = currentAmount % 5; // calculate remainder after even division
      amountInNickels = currentAmount - remainderAfterNickels; // amount in nickels
      numberOfNickels = amountInNickels / 5;		// number of nickels
      coinTypeCount[ 2 ] = numberOfNickels;		// assign number of nickels to index 2
      currentAmount = currentAmount - amountInNickels; // remaining amount, used to calculate pennies
      
      remainderAfterPennies = currentAmount % 1; // calculate remainder after even division
      amountInPennies = currentAmount - remainderAfterPennies; // amount in pennies
      numberOfPennies = amountInPennies / 1;		// number of pennies
      coinTypeCount[ 3 ] = numberOfPennies;		// assign number of pennies to index 3
      currentAmount = currentAmount - amountInPennies;  // currentAmount is now zero
		
      setAmountString( someAmount );   // calls setAmountString method of this class	
													// passes original amount (amount from main)			
	} // end setChange method		
		
	//****************************************************************		
} // end ChangeWindow class
 
 
//============================================
//============================================
 
 
// Project 2 class
 
package project2;
 
import java.awt.*;
import javax.swing.*;
 
 
 
public class Project2
{
	// the main method creates the changeWindow object 
   // the main method should repeatedly allow the user to 
	//		enter a change amount
   // an appropriate error message should be displayed if a value 
   //     outside the allowed range is entered
	public static void main( String[] args )
   {
		// local variable		
		int amount = 0;
			
     	// create a new change window
      ChangeWindow changeWindow = new ChangeWindow();	
      changeWindow.display();		// calls PaintComponent in ChangeWindow class
											// paints initial blank green window
											         				
		while( true )	// allow user to repeatedly enter amount
		{
			// allow user to enter an amount of change between 1 and 99 cents
        	String inputAmount =	
         JOptionPane.showInputDialog
				 ( "Enter an amount of change between 1 and 99 cents:" );	
				
			amount = Integer.parseInt( inputAmount );
				
			// display error if amount < 1 or amount > 99	
			if( amount < 1 || amount > 99 )
			{
				JOptionPane dialog = new JOptionPane(); 
				dialog.showMessageDialog( null, "This is an error, start over", "Error", 
														JOptionPane.ERROR_MESSAGE ); 
				return;
			}
	
			// the input value (amount)is passed to the setChange method in the
			//		ChangeWindow class
			changeWindow.setChange( amount );				
				
			// main does not have a Graphics object
			// after the setChange method (and setAmountString) are called, 
			//    the repaint method must be called
			// repaint causes the paintComponent method to be called in the ChangeWindow class
			// the paintComponent method has the Graphics object that must be used
			// 	for all painting
      	changeWindow.repaint();
			
			// allow user to enter another amount or quit				
			int response = JOptionPane.showConfirmDialog( null,
						"Enter another amount? No to Quit.",
						"Window Change Control", JOptionPane.YES_NO_OPTION );
						
			if( response == JOptionPane.NO_OPTION ||
					response == JOptionPane.CLOSED_OPTION )
			{
				return;
			}		
		}// end while	
	}// end main	
}// end Project2 class
 
 
//============================================
//============================================

Open in new window

Well i could have answered the question in principle: 'because it's because you *do* do what i suggested in the earlier work, but, taking the trouble to look, you have the below in ChangeWindow.paintComponent, which demonstrates what i said:
        for (Coins coins : Coins.values()) {
            coinColor = coins.getColor(); // invoke getColor for current coin type
 
            int coinSize = coins.getSize(); // invoke getSize for current coin type
            String coinDenomination = coins.getDenomination(); // invoke getDenomination for current coin type 
            for (int coinNumber = 0; coinNumber < coinTypeCount[typeOfCoin];
 
..................

Open in new window

Are you saying I already have what you were suggesting, or are you saying I still need to change something? Any guidance here would be extremely helpful.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
When a button is pressed, I need to call the paintComponent method of the CoinsDrawingPanel class.  
How do I call the paintComponent method in the CoinsDrawingPanel when a button is pressed?
>>>>>List<List<Coins>> is the container you need

I have not used this syntax, so it is a little above me right now.


>>>>>Well i could have answered the question in principle: 'because it's because you *do* do what i suggested in the earlier work, but, taking the trouble to look, you have the below in ChangeWindow.paintComponent, which demonstrates what i said:

Are you saying that because I *do* have the list of coins, iterate them, and paint them and offset them slightly on each iteration I am *not* able to see the painted coins?  I'm a little confused as to what you are trying to say here.


>>>>>It's not working in the newer project because you're not even attempting to do the same as i suggested, as you're doing in the older project

I am attempting to paint the coins in the new project the same way I painted them in the old project.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK, I just wrote a short button example.  I am hoping this will enlighten me and allow me to see what I am missing.  If anyone has any additional input, I am all ears.



package CoinButtonTest;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
//----------------------------------------------------
//----------------------------------------------------
 
// ButtonTest class
class CoinButtonTest extends JFrame
{
	// main method
	public static void main( String[] args )
	{
		JFrame coinButtonTest = new JFrame( "Coin Button Test" );
		coinButtonTest.getContentPane().add( new CoinButtonPanel( ) );
		coinButtonTest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		coinButtonTest.pack( );
		coinButtonTest.show( );
	}// end main	
}// end ButtonTest class
 
//----------------------------------------------------
//----------------------------------------------------
 
// ButtonPanel class
class CoinButtonPanel extends JPanel implements ActionListener
{
	private CoinDrawingPanel coinDrawing = new CoinDrawingPanel( );
	
	// create buttons
	private JButton quarterButton = new JButton( "25" );
	private JButton dimeButton = new JButton( "10" );	
	
	private JLabel textLabel;
	private String textLabelText = "Text goes here...";
	
	private int quarter = 0;
	private int dime = 1;			
	
	// constructor method
	CoinButtonPanel()
	{
		
		// 
   	quarterButton.setToolTipText( "Click this button to draw a quarter." );
		dimeButton.setToolTipText( "Click this button to draw a dime." );	
		
		quarterButton.addActionListener( this );
		dimeButton.addActionListener( this );
		
		// put buttons in a flow layout
		JPanel coinButtonPanel = new JPanel( );
		coinButtonPanel.setLayout( new FlowLayout( ) );
		coinButtonPanel.add( quarterButton );
		coinButtonPanel.add( dimeButton );
		
		textLabel = new JLabel( textLabelText, SwingConstants.LEFT );
		textLabel.setOpaque( true);
		textLabel.setBackground( Color.black );
		textLabel.setForeground( Color.yellow );
		
		// set layout and add buttons and drawing
		this.setLayout( new BorderLayout( ) );
		this.add( coinButtonPanel, BorderLayout.NORTH );
		this.add( coinDrawing, BorderLayout.CENTER );
		this.add( textLabel, BorderLayout.SOUTH);
	}// end constructor method
	
	// actionPerformed method
	public void actionPerformed( ActionEvent event )
	{
 
		if( event.getSource( ) == quarterButton )
		{
			//textLabelText = "Added one quarter.";
			coinDrawing.setCoin( quarter );
			//drawing.repaint( );
		}
		else if( event.getSource( ) == dimeButton )
		{
			//textLabelText = "Added one dime.";
			coinDrawing.setCoin( dime );
			//drawing.repaint( );
		}
	}// end actionPerformed method
}// end ButtonPanel class
 
//----------------------------------------------------
//----------------------------------------------------
 
// DrawingPanel class
class CoinDrawingPanel extends JPanel
{	
 
	// constants used for coin spacing
   private static final int SPACE_TO_COIN_TYPE = 90;      // x coordinate for every coin type
   private static final int COIN_OVERLAP = 30;            // y coordinate for every coin type
 
   // constant colors
   Color TEXT_COLOR = Color.BLACK;
   Color COIN_OUTLINE_COLOR = Color.BLACK;
	
	 // constants used for textAmountToDisplay spacing
   private static final int SPACE_TO_TEXT_FROM_LEFT = 95;      // x coordinate 
   private static final int SPACE_TO_TEXT_FROM_TOP = 350;      // y coordinate  
 
	private int typeOfCoin = 0;
	private int coinNumber = 0;
	private int currentCoin = 0;
	private int [ ] coinTypeCount = new int[ Coins.values( ).length ];
	
	private String textToDisplay = "";
	
	//private Coins coins;
	
	// constructor method
	CoinDrawingPanel( )
	{
		this.setBackground( Color.yellow );
		this.setPreferredSize( new Dimension( 400, 400 ) );	// size
	}
	
	// setCoin method
	public void setCoin( int passedCoin )
	{
		currentCoin = passedCoin;	// set current coin to passed coin
		repaint( );	// redraw it with new coin
	}
	
	//paintComponent method
	public void paintComponent( Graphics g )
	{
		super.paintComponent( g );
		
		int typeOfCoin = 0;
      int spaceToCoinType = 0;
		
		if( currentCoin == 0 )
		{
			textToDisplay = "Quarter";
			coinTypeCount[ 0 ]++;		
		}
		else if ( currentCoin == 1 )
		{
			textToDisplay = "Dime";
			coinTypeCount[ 1 ]++;	
		}
		
 		// draw the coins
		for (Coins coins: Coins.values())
      {                                       
         Color coinColor = coins.getColor( );               // invokes getColor of current coin type
         int coinSize = coins.getSize( );                   // invokes getSize of current coin type
         String coinDenomination = coins.getDenomination( );// invokes getDenomination of current coin type
			                                                                
         // the coinNumber integer is the loop control variable that varifies
         //                  from 0 to one less than the number of coins.  It is used to
         //                  compute the y coordinate of each successive coin.                        
         for (int coinNumber = 0; coinNumber < coinTypeCount[ typeOfCoin ]; coinNumber++)
         {
         	g.setColor( COIN_OUTLINE_COLOR );	
                  
            // Notice that if you pass the position of where to draw each coin, 
            //    you can greatly simplify the code. Notice too that I do not pass 
            //    the coin type but the coin is the object on which the method is 
            //    invoked.                        
            coins.draw( g , (typeOfCoin + 1) * SPACE_TO_COIN_TYPE, 
                                                (coinNumber + 1)* COIN_OVERLAP);
                                                                  
            g.setColor( TEXT_COLOR );      // text color (black)
            g.drawString( coinDenomination, ( SPACE_TO_COIN_TYPE * ( typeOfCoin + 1 ) ) + ( ( coinSize - 8 ) / 2 ) ,
                                    ( COIN_OVERLAP + ( ( coinSize + 8 ) / 2 ) ) + ( COIN_OVERLAP * coinNumber ) );  
						                     
         }                      
         typeOfCoin++;
			
      }  
		
		g.drawString( textToDisplay, SPACE_TO_TEXT_FROM_LEFT, SPACE_TO_TEXT_FROM_TOP );
		
	}// end paintComponent method
}// end DrawingPanel class
		
			
			

Open in new window

After writing my example, and adding more and more to it, I have decided to use it as my program.  I am no longer having the problem painting the coins.  
:-)