Java Reference
In-Depth Information
Example 11•18: GraphicsExampleFrame.java (continued)
// Tell the Print menu item what to do when selected
print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get the currently displayed example, and call
// the print method (defined below)
print(examples[tpane.getSelectedIndex()]);
}
});
// Tell the Quit menu item what to do when selected
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { System.exit(0); }
});
// In addition to the Quit menu item, also handle window close events
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
// Insert each of the example objects into the tabbed pane
for(int i = 0; i < examples.length; i++) {
GraphicsExample e = examples[i];
tpane.addTab(e.getName(), new GraphicsExamplePane(e));
}
}
/**
* This inner class is a custom Swing component that displays
* a GraphicsExample object.
*/
public class GraphicsExamplePane extends JComponent {
GraphicsExample example; // The example to display
Dimension size;
// How much space it requires
public GraphicsExamplePane(GraphicsExample example) {
this.example = example;
size = new Dimension(example.getWidth(), example.getHeight());
}
/** Draw the component and the example it contains */
public void paintComponent(Graphics g) {
g.setColor(Color.white); // set the background
g.fillRect(0, 0, size.width, size.height); // to white
g.setColor(Color.black); // set a default drawing color
example.draw((Graphics2D) g, this); // ask example to draw itself
}
// These methods specify how big the component must be
public Dimension getPreferredSize() { return size; }
public Dimension getMinimumSize() { return size; }
}
/** This method is invoked by the Print menu item */
public void print(final GraphicsExample example) {
// Start off by getting a printer job to do the printing
PrinterJob job = PrinterJob.getPrinterJob();
// Wrap the example in a Printable object (defined below)
// and tell the PrinterJob that we want to print it
Search WWH ::




Custom Search