|
Counters and
Accumulator We saw counters in Unit 3. We counted the number of correct answers to the food questions and the number of games played and the number of wins when we were rolling dice in Lab3e. In this Lab we are going to use accumulators and counters in the actionPerformed method | ||
|
Copy, paste and run this - you will need the cherries and the cupcake gifs from Unit 3 before you start. You can copy all the gifs from Unit 3 to Unit 4 if you wish to at this time.
When we click the cupcake JButton, we want it to tell us how many we are buying and how much it costs How many times we click will require a counter ( an integer variable) where we add 1 each
time Later we will figure out the total
| ||
|
To make the "cherries JButton work 1. In the actionPerformed method add this ( it might be good to do this for b2 at this time )
2. Between the b1 braces add the counter a1 = a1+1; //counter(add 1 each time b1 is clicked) 3. After the counter add the accumulator d1 = d1 + 0.79; //accumulator for cupcakes 4. After the accumulator build the String for the setText and place in the JTextField
Try the program now. It should work correctly for the cupcake. Fixing flaws Unfortunately doubles are not as easy work work with. In Unit one, we learned how to force them to two decimal place. We should probably round decimals off to 2 places now. 5. Add this to the declaration of global variable
section 6. Inside the actionPerformed method, inside the
conditional for b1, 7. Change the s1 line to this s1 = a1 + " for $" + ans; Now run the program and click b1 several times. It should always have 2 decimal places 8. Do similar things for JButton 2 . | ||
|
Now we need to get a grand total
for the cost of all the items you are buying
Your program should work correctly - please show me | ||
|
Assignment 50 points -Finish Lab4c1 Colorize it, and use fonts - see GUI notes for help. Make up reasonable prices for food or use mine.
To make this GUI perfect, you really need to add a clear button for the next person to use the order form. I could see a clear button in the SOUTH beside the JTextField or added to the top of p1 with dummy JLabels for spacing. If you add this, it is worth 5 points. When you click the clear button, all counters and accumulators are set back to 0 i.e. a1=0; etc. Try it. continue on to part 2 of Lab4c |