Displaying Graphics Examples

Example 12-20 shows the GraphicsExampleFrame class we’ve been using to display GraphicsExample implementations throughout this chapter. This program mainly demonstrates the Swing and Printing APIs, but is included here for completeness. The paintComponent( ) method of the GraphicsExamplePane inner class is where the draw( ) method of each GraphicsExample object is invoked. Although paintComponent( ) is declared as taking a Graphics object, in Java 1.2 and later it is always passed a Graphics2D object, which can be safely cast to that type.

Example 12-20. GraphicsExampleFrame.java

package je3.graphics; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.awt.print.*; /** * This class displays one or more GraphicsExample objects in a * Swing JFrame and a JTabbedPane */ public class GraphicsExampleFrame extends JFrame { public GraphicsExampleFrame(final GraphicsExample[ ] examples) { super("GraphicsExampleFrame"); Container cpane = getContentPane( ); // Set up the frame cpane.setLayout(new BorderLayout( )); final JTabbedPane tpane = new JTabbedPane( ); // And the tabbed pane cpane.add(tpane, BorderLayout.CENTER); // Add a menubar JMenuBar menubar = new JMenuBar( ); // Create the menubar this.setJMenuBar(menubar); // Add it to the frame JMenu filemenu = new JMenu("File"); // Create a File menu menubar.add(filemenu); // Add to the menubar JMenuItem print = new JMenuItem("Print"); // Create a Print item ...

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.