Java Reference
In-Depth Information
import java .awt. event . ;
import javax . swing .Timer;
import java . util . ;
public class TypingGame {
public static void main(String [] args) {
Timer t = new Timer(200, new TimerListener ()) ;
t. start() ;
JFrame frame = new JFrame () ;
frame. setVisible( true );
}
}
class TimerListener implements ActionListener {
ArrayList
<
Character
>
charList = new ArrayList
<>
() ;
public void actionPerformed(ActionEvent e)
{
charList .add(( char )(
+( int ) ((Math . random()
26)))) ;
'a'
System. out . println ( charList ) ;
}
}
First, note that in the Java standard libraries there are several classes that are named
Timer . Here, we want to use the class that is defined in javax.swing.Timer .Notethatwe
cannot simply import javax.swing.* . The reason is that there is another Timer class in
the package java.util.* and Java will not know which one to use. Next, note that the
above code needs to be written in the file TypingGame.java . Remember that inside every
Java file we can have several classes, where exactly one of them can be public .Theclass
that is public must have exactly the same name as the name of the Java file.
The first parameter of the constructor of the Timer class determines the delay between
method calls in milliseconds. The second parameter of the constructor is an object that
belongs to a class that implements the ActionListener interface. Here is the code that
defines the interface (it is part of java.util.* ).
interface ActionListener {
public void actionPerformed(ActionEvent e) ;
}
After the timer is started, the actionPerformed method will be repeatedly invoked.
The Timer class knows that it can call the actionPerformed method on the input object
because the object must belong to a class that implements the interface ActionListener .
The start method is used to start the timer. If we want to stop it, we can use the stop
method.
Thelasttwolinesofthe main method create a window and make it visible. This pre-
vents the program from immediately terminating. The actionPerformed method creates a
random character, adds it to the ArrayList , and prints the list. Note that the cast (char)
can convert an integer to the character that has that ASCII code. The code also explicitly
references
: 97. Note that hard-coding the
number 97 in the program would be an inferior choice because the ASCII table can poten-
tially change. The code in the actionPerformed method generates a new random character,
adds it to the ArrayList , and then the ArrayList is printed. Every 200 milliseconds, the
actionPerformed method is called.
a
, which is converted to the ASCII code of
a
'
'
'
'
 
Search WWH ::




Custom Search