Java Reference
In-Depth Information
Chapter 12
More techniques and tips
12.1 Introduction
In Part I of this topic and Web Course we tried to provide an introduction to the
essential elements of the Java language that allow you to begin creating useful
programs in short order. In this chapter we discuss several practical techniques
that will expand the capabilities of your programs. We begin with a discussion
of how to print your graphics displays and then discuss several user interface
features such as cursor icons and popup menus, handling keystrokes, and audio.
We also review various ways to improve the speed of Java programs.
12.2 Printing
Java 1.1 provided the capability to print what is displayed on a Java component
[1]. Java 1.2 added Java 2D, which expanded the print capabilities to support
greater control over multiple page printing and other features. (We should point
out that printing only works with applications since the SecurityManager in
browser JVMs blocks printing from applets.)
In Java graphics the usual job of the paint() method in AWT and the paint-
Component() method in Swing is to send drawing commands to the monitor
screen. Java printing simply entails sending drawing commands to the printer
instead of the monitor screen. In rendering Java components, we have seen that a
Graphics context object is passed to the paint() and paintComponent()
methods. To render to the printer, you obtain an instance of PrintGraphics ,
which is a subclass of Graphics , and pass it to the paint() or paint-
Component() method. The graphics context drawing commands then work as
usual except that the drawing will be on the printer paper rather than on the
screen.
Figure 12.1 shows the user interface for the program PrintTestApp ,which
displays an image in the frame and holds a menu bar with a dropdown menu to
select whether to print or quit the program. The following code snippet from the
program shows the steps needed to obtain the print dialog from the host system
390
Search WWH ::




Custom Search