-3

I want to make a program that displays random numbers, bliking one at a time in a JLabel or just in the console. I am making a game, where the player needs to remember the number that was displayed two blinks back in time. Does anyone know how to make the numbers blink?

thorbear
  • 15
  • 1
  • 1
  • 4
  • You should show your work so far, so that we know what you have exact problems with. Do you know how to display a JLabel? Do you know how to change the value? If yes, then probably you can use Timer class (http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) to schedule a label update with a specific interval. – Gerino Jan 22 '15 at 09:50
  • I am pretty new at this, but I do know how to display a JLabel. What I don't quite understand, is how to make a new number come up every time the JLabel blinks. – thorbear Jan 22 '15 at 09:53

1 Answers1

0

I unfortunately don't have any GUI project handy to test it out (I might in a moment as a command line one), but I think that one way to do it is:

(I've removed the HideTask, as it gives some trouble when you want to run it again, and I don't think the task at hand really needs it - just call sleep() :) )

class ShowTask extends TimerTask {
    JLabel label;
    Random generator = new Random();
    //HideTask hTask;
    //java.util.Timer timer = new java.util.Timer();
    long period = 500; // ms

    public Task(JLabel pLabel){
        label = pLabel;
        //hTask = new HideTask(pLabel);
    }

    public void run(){
        int i = generator.nextInt(100);
        setLabel(i);
        // if you want it to go SHOW HIDE SHOW HIDE instead of SHOW SHOW SHOW then:
        //timer.schedule(hTask, period);
        // just wait
        Thread.sleep(period);
        hideLabel();
    }

    void setLabel(int i){
        ...
    }
}
/*
class HideTask extends TimerTask {
    JLabel label;

    public HideTask(JLabel pLabel){
        label = pLabel;
    }

    public void run(){
        hideLabel();
    }

    void hideLabel(){
        ...
    }
}
*/

when you want to start:

ShowTask task = new ShowTask();
long delay = 0; // ms 
long period = 1000; // ms
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(task, delay, period);

Note, that it wasn't tested and it is just the first concept I come up with, but maybe you can work forward from it.

Gerino
  • 1,943
  • 1
  • 16
  • 21