Java Reference
In-Depth Information
You can now declare, instantiate, and register the listener as follows:
private ButtonHandler pbHandler;
//declare the listener
pbHandler = new ButtonHandler();
//instantiate the object
//register the listener with each button
candyB.addActionListener(pbHandler);
chipsB.addActionListener(pbHandler);
gumB.addActionListener(pbHandler);
cookiesB.addActionListener(pbHandler);
exitB.addActionListener(pbHandler);
Next, we describe the method sellProduct.
The definition of this method is similar to the one we designed for the non-GUI
program. (We give the definition here for the sake of completeness.) This method
attempts to sell a particular product selected by the customer. The candy machine
contains four dispensers, which correspond to the four products. These dispensers will
be declared as instance variables. Therefore, the dispenser of the product to be sold
and the name of the product are passed as parameters to this method. Because the
cash register will be declared as an instance variable, this method can directly access the
cash register.
This definition of the method sellProduct is:
Method
sellProduct
8
private void sellProduct(Dispenser product, String productName)
{
int coinsInserted = 0;
int price;
int coinsRequired;
String str;
if (product.getCount() > 0)
{
price = product.getProductCost();
coinsRequired = price - coinsInserted;
while (coinsRequired > 0)
{
str = JOptionPane.showInputDialog("To buy "
+ productName
+ " please insert "
+ coinsRequired + " cents");
coinsInserted = coinsInserted
+ Integer.parseInt(str);
coinsRequired = price - coinsInserted;
}
Search WWH ::




Custom Search