FileDocCategorySizeDatePackage
ScoreLabel.javaAPI DocExample2886Sat Apr 17 15:00:58 BST 2004javathreads.examples.ch07.example2

ScoreLabel

public class ScoreLabel extends JLabel implements CharacterListener

Fields Summary
private volatile int
score
private int
char2type
private CharacterSource
generator
private CharacterSource
typist
private Lock
scoreLock
Constructors Summary
public ScoreLabel(CharacterSource generator, CharacterSource typist)


         
        this.generator = generator;
        this.typist = typist;
        if (generator != null)
            generator.addCharacterListener(this);
        if (typist != null)
            typist.addCharacterListener(this);
    
public ScoreLabel()

        this(null, null);
    
Methods Summary
public voidnewCharacter(CharacterEvent ce)

        scoreLock.lock();
        try {
            if (ce.source == generator) {
                if (char2type != -1) {
                    score--;
                    setScore();
                }
                char2type = ce.character;
            }
            else {
                if (char2type != ce.character) {
                    score--;
                } else {
                    score++;
                    char2type = -1;
                }
            }
            setScore();
        } finally {
            scoreLock.unlock();
        }
    
public voidresetGenerator(CharacterSource newGenerator)

        try {
            scoreLock.lock();
            if (generator != null)
                generator.removeCharacterListener(this);
            generator = newGenerator;
            if (generator != null)
                generator.addCharacterListener(this);
        } finally {
            scoreLock.unlock();
        }
    
public voidresetScore()

       try {
           scoreLock.lock();
           score = 0;
           char2type = -1;
           setScore();
       } finally {
           scoreLock.unlock();
       }
    
public voidresetTypist(CharacterSource newTypist)

        try {
            scoreLock.lock();
            if (typist != null)
                typist.removeCharacterListener(this);
            typist = newTypist;
            if (typist != null)
                typist.addCharacterListener(this);
        } finally {
            scoreLock.unlock();
        }
    
private voidsetScore()

	if (SwingUtilities.isEventDispatchThread())
	    setText(Integer.toString(score));
	else try {
	    SwingUtilities.invokeAndWait(new Runnable() {
	    	public void run() {
		    setText(Integer.toString(score));
		}
	    });
	} catch (InterruptedException ie) {
	} catch (InvocationTargetException ite) {}