17.1 Ringing the Bell
In the old days, dumb computer terminals had a bell that would beep
when they received the ASCII
BEL character (\u0007). Modern computer hardware has retained the
ability to create an unpleasant-sounding beep, even if no speakers
are plugged in, if audio drivers are misconfigured, or if system
volume has been turned down. In a sense, the hardware bell is a sound
of last resort, and you can ring it when it is critical that you
attract the user's attention.There are two ways to ring this bell. In modern operating systems,
the command-line interface often emulates an old-style terminal, and
some of these terminal emulators respond to the BEL character. Thus,
on many platforms, a command-line application can make a sound by
printing the Unicode character \u0007 to
System.out.Applets and GUI-based applications don't typically
do console input and output, and may be launched in such a way that
output to System.out is not directed to a terminal
emulator. In Java 1.1 and later, these applications can create a beep
with the beep(
) method of the
java.awt.Toolkit class. (Console-based
applications can do this as well, of course, but at the cost of
increased startup time to load AWT classes.)Example 17-1 illustrates both techniques in a
console-based application. GUI-based applications should use
Component.getToolkit(
) to get a Toolkit object,
instead of Toolkit.getDefaultToolkit( ).
Example 17-1. Beep.java
package je3.sound;
// Ring the bell!
public class Beep {
public static void main(String[ ] args) {
// In terminal-based applications, this is a non-portable, unreliable
// way to sound the terminal bell (if there is one) and get the
// user's attention. \u0007 is the ASCII BEL or Ctrl-G character.
System.out.println("BEEP\u0007!");
// For applications that can use AWT, there is another way
// to ring the bell.
String[ ] words = new String[ ] {
"Shave ", "and ", "a ", "hair", "cut ", "two ", "bits."
};
int[ ] pauses = new int[ ] { 300, 150, 150, 250, 450, 250, 1 };
for(int i = 0; i < pauses.length; i++) {
// Ring the bell using AWT
java.awt.Toolkit.getDefaultToolkit( ).beep( );
System.out.print(words[i]);
System.out.flush( );
// Wait a while before beeping again.
try { Thread.sleep(pauses[i]); } catch(InterruptedException e) { }
}
System.out.println( );
}
}