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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.