FileDocCategorySizeDatePackage
ScoreLabel.javaAPI DocExample2356Sat Apr 17 13:46:26 BST 2004javathreads.examples.ch03.example1

ScoreLabel

public class ScoreLabel extends JLabel implements CharacterListener

Fields Summary
private volatile int
score
private int
char2type
private CharacterSource
generator
private CharacterSource
typist
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 synchronized voidnewCharacter(CharacterEvent ce)

        // Previous character not typed correctly - 1 point penalty
        if (ce.source == generator) {
            if (char2type != -1) {
                score--;
                setScore();
            }
            char2type = ce.character;
        }

        // If character is extraneous - 1 point penalty
        // If character does not match - 1 point penalty
        else {
            if (char2type != ce.character) {
                score--;
           } else {
               score++;
               char2type = -1;
           }
           setScore();
       }
    
public synchronized voidresetGenerator(CharacterSource newGenerator)

        if (generator != null)
            generator.removeCharacterListener(this);
        generator = newGenerator;
        if (generator != null)
            generator.addCharacterListener(this);        
    
public synchronized voidresetScore()

        score = 0;
        char2type = -1;
        setScore();
    
public synchronized voidresetTypist(CharacterSource newTypist)

        if (typist != null)
            typist.removeCharacterListener(this);
        typist = newTypist;
        if (typist != null)
            typist.addCharacterListener(this);
    
private voidsetScore()

        // This method will be explained later in chapter 7
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                setText(Integer.toString(score));
            }
        });