//======================================================================//  PROJECT:            _programming.java_//  FILE:               SodaPop.java//  PURPOSE:            Chapter 5 lablet//  VERSION:            1.1//  TARGET:             Java v1.1//  UPDATE HISTORY:     1.1     10/2/98     new documentation and 1.1 compliance//                      1.0     10/9/97     the version in _p.j_//======================================================================//------------------------------- NOTES --------------------------------/*    We've simplified this applet from the one in the text by splitting    off the money-related buttons into a separate class.	    We're back to an applet that actually does something.  Don't worry    about the details of event handling, but in brief we've made a class    we call Listener that receives events generated by clicks in the buttons    and then calls the appropriate method in the SodaPop class.  As a    consequence of this organization, we must write a collection of methods    (like processNickelButton() and processColaButton()) that will be called    from the Listener object, in much the same way that init() and paint()    are called from outside the applet.*///------------------------------ IMPORTS -------------------------------import java.awt.*;import java.awt.event.*;import java.applet.*;//=========================== SodaPop CLASS ============================/** * This class simulates a soda machine.  It is organized into two * functional parts: a panel on the left that simulates insertion * of coins and a panel on the right that "dispenses" a soda (by * placing an appropriate message in the display at the bottom) * if the user has inserted a sufficient amount of money. */public class SodaPop extends Applet{    //------------------------------ DATA ------------------------------					   	private MoneyPanel  money;         // to simulate coin insertion and return    private ChoicePanel choices;       // for drink selection buttons    private TextField   display;       // for status messages	    private int         amount,        // amount available for purchase                         cost,          // price of a drink                        numberColas;   // colas currently on hand	    private Listener    myListener = new Listener(this);	    //----------------------- THE USUAL METHODS ------------------------	    /**     * Lay out the two control panels and set the initial values     * for the cost of a soda and the number of colas remaining.     */    public void init()    {        setLayout(new BorderLayout());        setBackground(Color.red);        choices = new ChoicePanel(myListener);        add("East", choices);		        money = new MoneyPanel(myListener);        add("West", money);        display = new TextField();        display.setBackground(Color.white);        display.setForeground(Color.red);        display.setFont(new Font("Helvetica", Font.BOLD, 12));        add("South", display);		        cost = 75;        numberColas = 5;			    }	    /**     * Paint the logo in the middle of the applet's frame.     */    public void paint(Graphics g)    {    	Dimension d = getSize();        int xStart = d.width / 2 - 20;        int yStart = d.height / 2 - 80;		        g.setFont(new Font("TimesRoman", Font.BOLD, 36));        g.setColor(Color.white);        g.drawString("S", xStart, yStart);        g.drawString("O", xStart, yStart + 20);        g.drawString("D", xStart, yStart + 40);        g.drawString("A", xStart, yStart + 60);        g.drawString("P", xStart, yStart + 80);        g.drawString("O", xStart, yStart + 100);        g.drawString("P", xStart, yStart + 120);		        g.setFont(new Font("TimesRoman", Font.ITALIC, 18));        g.setColor(Color.white);        g.drawString("Insert 75 cents ...", xStart - 20, yStart + 160);    }	    //--------------- OUR OWN METHODS TO RESPOND TO CLICKS -------------	    /**     * Deal with a click on the nickel button.     */    void processNickelButton()    {        display.setText("Nickel inserted...");        amount += 5;    }    /**     * Deal with a click on the dime button.     */    void processDimeButton()    {        display.setText("Dime inserted...");        amount += 10;    }    /**     * Deal with a click on the quarter button.     */    void processQuarterButton()    {        display.setText("Quarter inserted...");        amount += 25;    }    /**     * In response to a click on the return button,     * display the amount returned and set the amount     * back to zero.     */    void processReturnButton()    {        String amountString;        int dollars = amount / 100;        int pennies = amount % 100;		        if (pennies < 10)        {            amountString = new String("$" + dollars + ".0" + pennies);        }        else        {            amountString = new String("$" + dollars + "." + pennies);        }        display.setText(amountString + " returned.");        amount = 0;    }    /**     * Try to "sell" a cola.     */    void processColaButton()    {        if (amount >= cost)        {            display.setText("COLA dispensed!!!");            amount -= cost;            numberColas--;        }        if (numberColas <= 0)        {            choices.disable("COLA");        }    }    /**     * Try to "sell" a diet soda.     */    void processDietButton()    {        if (amount >= cost)        {            display.setText("DIET dispensed!!!");            amount -= cost;        }    }    /**     * Try to "sell" a caffein-free, sugarless, acid-free, clear soda     * (sometimes called "water").     */    void processLiteButton()    {        if (amount >= cost)        {            display.setText("LITE dispensed!!!");            amount -= cost;        }    }    /**     * Try to "sell" a root beer.     */    void processRootButton()    {        if (amount >= cost)        {            display.setText("ROOT dispensed!!!");            amount -= cost;        }    }}//========================= MoneyPanel CLASS ===========================/** * This class is primarily for display purposes in the SodaPop applet. * It is, basically, a holder for the four money-related buttons. * It does do some event-handling in response to button clicks, but   * for the purposes of this lab, you can ignore anything that has the * word "Listener" in it. */class MoneyPanel extends Panel{    private Button bNickel = new Button("Nickel"),            bDime = new Button("Dime"),            bQuarter = new Button("Quarter"),            bReturn = new Button("Return Coins");					    /**     * Lay out the nickel, dime, and quarter buttons in a 3-by-1     * grid and then place them and the return button in a      * 2-by-1 grid (giving a really big return button).     */    public MoneyPanel(Listener theListener)    {        bNickel.addActionListener(theListener);        bDime.addActionListener(theListener);        bQuarter.addActionListener(theListener);        bReturn.addActionListener(theListener);		        setBackground(Color.blue);        setForeground(Color.white);        setLayout(new GridLayout(2,1, 5, 5));        Panel p = new Panel();        p.setLayout(new GridLayout(3,1, 5, 5));        p.add(bNickel);        p.add(bDime);        p.add(bQuarter);		        add(p);        add(bReturn);    }}//========================= ChoicePanel CLASS ==========================/** * Like the MoneyPanel class, this class is primarily a  * holder for the four drink buttons.  Again, pay no attention * to anything with the word "Listener" in it. */class ChoicePanel extends Panel{    private Button bCola = new Button("COLA"),            bDiet = new Button("DIET"),            bLite = new Button("LITE"),            bRoot = new Button("ROOT BEER");					    /**     * Construct a new ChoicePanel object by setting     * the colors and layout and then adding the four     * drink buttons.     */    public ChoicePanel(Listener theListener)    {        bCola.addActionListener(theListener);        bDiet.addActionListener(theListener);        bLite.addActionListener(theListener);        bRoot.addActionListener(theListener);		        setBackground(Color.blue);        setForeground(Color.white);	        setLayout(new GridLayout(4,1));        add(bCola);		add(bDiet);        add(bLite);        add(bRoot);    }        /**     * Turn off one of the buttons.     */    public void disable(String name)    {        if (name.equals("COLA"))        {            bCola.setEnabled(false);        }    }}//=========================== Listener CLASS ===========================/** * This class is designed to respond to button clicks * from the various buttons in our applet by calling * the applet's appropriate process() function. * For now, it's not necessary to understand what's * going on here--all will be made clear in Chapter 6. */class Listener implements ActionListener{    private SodaPop theApplet;    /*     * Construct a Listener object by registering     * the applet that will be responding to the     * events (so this object knows the SodaPop     * object that owns the "process..." functions).     */    public Listener(SodaPop theBigBoss)    {        theApplet = theBigBoss;    }	    public void actionPerformed(ActionEvent e)    {        String bttnName = e.getActionCommand();		        //------ Deal with clicks on the money buttons -----		        if (bttnName.equals("Nickel"))        {            theApplet.processNickelButton();        }        else if (bttnName.equals("Dime"))        {            theApplet.processDimeButton();        }        else if (bttnName.equals("Quarter"))        {            theApplet.processQuarterButton();        }        else if (bttnName.equals("Return Coins"))        {            theApplet.processReturnButton();        }		        //------ Deal with clicks on the soda buttons ------		        if (bttnName.equals("COLA"))        {            theApplet.processColaButton();        }        else if (bttnName.equals("DIET"))        {            theApplet.processDietButton();        }        else if (bttnName.equals("LITE"))        {            theApplet.processLiteButton();        }        else if (bttnName.equals("ROOT BEER"))        {            theApplet.processRootButton();        }    }}