This site requires JavaScript, please enable it in your browser!
Greenfoot back
Gaming_100
Gaming_100 wrote ...

2017/4/5

How to make a Simple counter

Gaming_100 Gaming_100

2017/4/5

#
Hello! I was wondering how to make a button that when i press it i add +1 point to a variable. It seems very simple i know but i just can't figure out how to do it! Also how do i display the number in a terminal window? or as text on screen? Thanks very much! - Gaming_100
Super_Hippo Super_Hippo

2017/4/5

#
1
2
3
4
5
6
7
8
9
10
11
//in an Actor subclass, the button
private int counter = 0;
 
public void act()
{
    if (Greenfoot.mousePressed(this))
    {
        counter++;
        //display text
    }
}
To print it to the terminal window, you can use:
1
System.out.println("Counter = " + counter);
To make it visible in the world, you can either use the showText method in the world
1
getWorld().showText("Counter = " + counter, 100, 100);
or you have an actor, give it an image with the value of the variable and add it to the world.
Gaming_100 Gaming_100

2017/4/5

#
You are the best! Thanks very much!
You need to login to post a reply.