This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Counter

By: a guest on Jan 24th, 2014  |  syntax: None  |  size: 1.96 KB  |  views: 4  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)  
  2. import java.awt.Color;  
  3.  
  4. /**
  5.  * A simple counter with graphical representation as an actor on screen.
  6.  *  
  7.  * @author mik
  8.  * @version 1.0
  9.  */  
  10. public class Counter extends Actor  
  11. {  
  12.     private static final Color transparent = new Color(0,0,0,0);  
  13.     private GreenfootImage background;  
  14.     private int value;  
  15.     private int target;  
  16.     /**
  17.      * Create a new counter, initialised to 0.
  18.      */  
  19.     public Counter()  
  20.     {  
  21.         background = getImage();  // get image from class  
  22.         value = 0;  
  23.         target = 0;  
  24.         updateImage();  
  25.     }  
  26.     /**
  27.      * Animate the display to count up (or down) to the current target value.
  28.      */  
  29.     public void act()  
  30.     {  
  31.         if (value < target) {  
  32.             value++;  
  33.             updateImage();  
  34.         }  
  35.         else if (value > target) {  
  36.             value--;  
  37.             updateImage();  
  38.         }  
  39.     }  
  40.     /**
  41.      * Add a new score to the current counter value.
  42.      */  
  43.     public void add(int score)  
  44.     {  
  45.         target += score;  
  46.     }  
  47.  
  48.     /**
  49.      * Return the current counter value.
  50.      */  
  51.     public int getValue()  
  52.     {  
  53.         return value;  
  54.     }  
  55.  
  56.     /**
  57.      * Set a new counter value.
  58.      */  
  59.     public void setValue(int newValue)  
  60.     {  
  61.         target = newValue;  
  62.         value = newValue;  
  63.         updateImage();  
  64.     }  
  65.  
  66.     /**
  67.      * Update the image on screen to show the current value.
  68.      */  
  69.     private void updateImage()  
  70.     {  
  71.         GreenfootImage image = new GreenfootImage(background);  
  72.         GreenfootImage text = new GreenfootImage("" + value, 22, Color.BLACK, transparent);  
  73.         image.drawImage(text, (image.getWidth()-text.getWidth())/2,  
  74.                         (image.getHeight()-text.getHeight())/2);  
  75.         setImage(image);  
  76.     }  
  77. }
clone this paste RAW Paste Data