Home  Listings  By Name  By Subject  Email  www.tomswan.com  Help 

Java 2 Just Click! Solutions

Chapter 23 Listings

© 2001 by Tom Swan. All rights reserved. Updated: 6/4/01 12:20:54 PM

Return to Listings page
Switch to Solutions by name page
Switch to Solutions by subject page


Listing 23-1 GraphicsApp/GraphicsApp.java Page 512

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class GraphicsApp extends JFrame {
006: 
007: // Constructor 
008:  public GraphicsApp() {
009:   // Select local system look and feel
010:   try {
011:    UIManager.setLookAndFeel(
012:     UIManager.getCrossPlatformLookAndFeelClassName());
013:   } catch (Exception e) { }
014:   // End program when window closes
015:   addWindowListener(new WindowAdapter() {
016:    public void windowClosing(WindowEvent e) {
017:     System.exit(0);
018:    }
019:   });
020:  }
021: 
022:  public void paint(Graphics g) {
023:   // Get window size
024:   Rectangle r = getBounds(null);
025:   // Paint background yellow
026:   g.setColor(Color.yellow);
027:   g.fillRect(0, 0, r.width, r.height);
028:   // Outline window in black
029:   g.setColor(Color.black);
030:   g.drawRect(0, 0, r.width, r.height);
031:   // Draw grid inside window
032:   for (int h = 0; h < r.height; h += 10)
033:    g.drawLine(0, h, r.width, h);
034:   for (int v = 0; v < r.width; v += 10)
035:    g.drawLine(v, 0, v, r.height);
036:   // Draw overlapping round rectangles
037:   int cx = r.width / 8;
038:   int cy = r.height / 3;
039:   int w = (r.width / 4) * 3;
040:   int h = cy;
041:   g.setColor(Color.gray);
042:   g.fillRoundRect(cx - 4, cy - 4, w, h, 10, 10);
043:   g.setColor(Color.blue);
044:   g.fillRoundRect(cx + 4, cy + 4, w, h, 10, 10);
045:   // Draw text inside outer rectangle
046:   Font f = new Font("TimesRoman", 
047:    Font.BOLD + Font.ITALIC, 24);
048:   g.setFont(f);
049:   g.setColor(Color.orange);
050:   g.drawString("Java 2 Just Click! Solutions", cx + 25, cy + 36);
051:   g.drawString("Graphics Demonstration", cx + 35, cy + 66);
052:  }
053: 
054:  public static void main(String[] args) {
055:   GraphicsApp app = new GraphicsApp();
056:   app.setTitle("Graphics Demonstration (application)");
057:   app.setSize(450, 280);
058:   app.show();
059:  }
060: }
Return to top

Listing 23-2 Gradient/Gradient.java Page 517

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class Gradient extends JFrame {
006: 
007: // Constructor 
008:  public Gradient() {
009:   // Select local system look and feel
010:   try {
011:    UIManager.setLookAndFeel(
012:     UIManager.getCrossPlatformLookAndFeelClassName());
013:   } catch (Exception e) { }
014:   // End program when window closes
015:   addWindowListener(new WindowAdapter() {
016:    public void windowClosing(WindowEvent e) {
017:     System.exit(0);
018:    }
019:   });
020:  }
021: 
022:  public void paint(Graphics g) {
023:   int increment = 40;
024:   Rectangle r = getBounds(null);
025:   Color c = new Color(50, 255, 50);
026:   int x = 0;
027:   while (x < r.width) {
028:    g.setColor(c);
029:    g.fillRect(x, 0, x + increment, r.height);
030:    c = c.darker();
031:    x += increment;
032:   }
033:  }
034: 
035:  public static void main(String[] args) {
036:   Gradient app = new Gradient();
037:   app.setTitle("Gradient Color Demonstration");
038:   app.setSize(320, 240);
039:   app.show();
040:  }
041: }
Return to top

Listing 23-3 FontDemo/FontDemo.java Page 521

Return to top
001: import javax.swing.*;
002: import javax.swing.event.*;
003: import java.awt.*;
004: import java.awt.event.*;
005: 
006: // Window frame class for showing selected font sample
007: class FontSample extends JFrame {
008:  Font font;    // Currently shown font
009:  String text;  // Sample text to display
010: 
011:  // Constructor
012:  public FontSample() {
013:   super();
014:   font = null;
015:   text = "Abcdefg 1234567890 !@#$%^&*()";
016:   setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
017:   setSize(425, 120);
018:  }
019: 
020:  // Called before showing window
021:  public void changeFont(Font f) {
022:   font = f.deriveFont(24.0f);   // Resize to 24 pts
023:   setTitle(font.getFontName()); // Title = font name
024:   if (isShowing()) repaint();   // Repaint if already visible
025:  }
026: 
027:  // Paint sample text using current font in window
028:  public void paint(Graphics g) {
029:   Rectangle r = getBounds(null);
030:   g.setColor(Color.white);  // Erase background to white
031:   g.fillRect(0, 0, r.width, r.height);
032:   if (font != null) {
033:    g.setFont(font);
034:    g.setColor(Color.black);
035:    g.drawString(text, 10, r.height / 2);
036:   }
037:  }
038: }
039: 
040: // Main program class
041: public class FontDemo extends JFrame {
042:  final protected Font[] fonts;           // Array of fonts
043:  final protected FontSample fontSample;  // Sample window
044: 
045: // Constructor 
046:  public FontDemo() {
047:   super();
048:   // Select local system look and feel
049:   try {
050:    UIManager.setLookAndFeel(
051:     UIManager.getSystemLookAndFeelClassName());
052:   } catch (Exception e) { }
053:   // End program when window closes
054:   addWindowListener(new WindowAdapter() {
055:    public void windowClosing(WindowEvent e) {
056:     System.exit(0);
057:    }
058:   });
059: 
060:   // Create child sample font window
061:   fontSample = new FontSample();
062: 
063:   // Loading fonts may take a while; tell user
064:   System.out.print("Loading font names...");
065: 
066:   // Get available fonts in 1pt sizes
067:   GraphicsEnvironment ge = 
068:    GraphicsEnvironment.getLocalGraphicsEnvironment();
069:   fonts = ge.getAllFonts();
070: 
071:   // Create a JComboBox object for listing font names
072:   JComboBox fontBox = new JComboBox();
073:   for (int i = 0; i < fonts.length; i++)
074:    fontBox.addItem(fonts[i].getFontName());
075:   fontBox.setEditable(false);
076: 
077:   // Respond to item selection
078:   fontBox.addActionListener(
079:    new ActionListener() {
080:     public void actionPerformed(ActionEvent e) {
081:      JComboBox box = (JComboBox)e.getSource();
082:      int fontIndex = box.getSelectedIndex();
083:      fontSample.changeFont(fonts[fontIndex]);
084:      fontSample.show();
085:     }
086:    }
087:   );
088:   
089:   System.out.println("/nSelect font for a sample"); 
090:   Container content = getContentPane();
091:   content.setLayout(new FlowLayout());
092:   content.add(new JLabel("Available fonts"));
093:   content.add(fontBox);
094:  }
095: 
096:  public static void main(String[] args) {
097:   FontDemo app = new FontDemo();
098:   app.setTitle("Font Demonstration");
099:   app.setSize(320, 240);
100:   app.show();
101:  }
102: }
Return to top

Listing 23-4 ShowPic/ShowPic.java Page 530

Return to top
001: import java.applet.*;
002: import java.awt.*;
003: 
004: public class ShowPic extends Applet
005:  implements Runnable {
006: 
007:  // Instance variables
008:  Image pic;             // GIF image producer
009:  int picID;             // Arbitrary image ID
010:  MediaTracker tracker;  // Tracks loading of image
011:  Thread loadingThread;  // Thread for loading image
012:  String filename = "ksc-01pp-0287.jpg";  // File name
013: 
014:  // Initialize applet
015:  public void init() {
016:   // Create MediaTracker object
017:   tracker = new MediaTracker(this);
018:   // Start image loading
019:   pic = getImage(getDocumentBase(), filename);
020:   picID = 0;
021:   tracker.addImage(pic, picID);
022:   // Create thread to monitor image loading
023:   loadingThread = new Thread(this);
024:   loadingThread.start();
025:  }
026: 
027:  // Run loading thread
028:  // Allows other processes to run while loading
029:  // the image data
030:  public void run() {
031:   try {
032:    tracker.waitForID(picID);
033:   } catch (InterruptedException ie) {
034:    return;
035:   }
036:   repaint();  // Cause paint() to draw loaded image
037:  }
038: 
039:  // Paint window contents
040:  // Displays loading or error message until
041:  // image is ready, then shows image
042:  public void paint(Graphics g) {
043:   if (tracker.isErrorID(picID))
044:    g.drawString("Error loading " + filename, 10, 20);
045:   else if (tracker.checkID(picID))
046:    g.drawImage(pic, 0, 0, this);
047:   else
048:    g.drawString("Loading " + filename, 10, 20);
049:  }
050: }
Return to top

Listing 23-5 Offscreen/Offscreen.java Page 536

Return to top
001: import java.applet.*;
002: import java.awt.*;
003: import java.util.Random;
004: 
005: public class Offscreen extends Applet
006:  implements Runnable {
007: 
008:  // Instance variables
009:  Thread drawingThread;
010:  Image offscreenImage;
011:  Graphics offscreenContext;
012:  Random gen;
013:  boolean imageReady = false;
014:  int imageW, imageH;
015:  int numOvals = 100;
016: 
017:  // Initialize applet
018:  public void init() {
019:   // Size applet window
020:   imageW = 320;
021:   imageH = 240;
022:   resize(imageW, imageH);
023:   // Construct random number generator
024:   gen = new Random();
025:   // Create offscreen image and Graphics context
026:   offscreenImage = createImage(imageW, imageH);
027:   offscreenContext = offscreenImage.getGraphics();
028:  }
029: 
030:  // Create and start drawing thread
031:  public void start() {
032:   drawingThread = new Thread(this);
033:   drawingThread.start();
034:  }
035: 
036:  // Return positive integer at random between
037:  // low and high. Assumes low < high and are positive
038:  public int nextInt(int low, int high) {
039:   return low + (Math.abs(gen.nextInt()) % (high - low));
040:  }
041: 
042:  // Create image using separate thread
043:  public void run() {
044:   // Paint image background white
045:   offscreenContext.setColor(getBackground());
046:   offscreenContext.fillRect(0, 0, imageW, imageH);
047:   // Create and paint ovals at random
048:   for (int i = 0; i < numOvals; i++) {
049:    // Select oval color at random
050:    Color c = new Color(nextInt(0, 0xffffff));
051:    offscreenContext.setColor(c);
052:    // Select oval position
053:    int x = nextInt(20, imageW - 20);
054:    int y = nextInt(20, imageH - 20);
055:    // Calculate oval width and height
056:    // so it remains inside image boundaries
057:    int w = nextInt(10, Math.min(imageW - x, x));
058:    int h = nextInt(10, Math.min(imageH - y, y));
059:    // Draw oval to offscreen image
060:    offscreenContext.fillOval(x, y, w, h);
061:    Thread.yield();
062:   }
063:   imageReady = true;
064:   repaint();
065:  }
066: 
067:  // Paint window contents
068:  public void paint(Graphics g) {
069:   if (imageReady) {
070:    showStatus("Showing image...");
071:    g.drawImage(offscreenImage, 0, 0, this);
072:   } else {
073:    g.setColor(getBackground());
074:    g.fillRect(0, 0, imageW, imageH);
075:    showStatus("Preparing image...");
076:   }
077:  }
078: 
079:  // Override inherited update() method
080:  // to prevent screen flicker
081:  public void update(Graphics g) {
082:   paint(g);
083:  }
084: }
Return to top

Listing 23-6 Filter/Filter.java Page 541

Return to top
001: import java.applet.*;
002: import java.awt.*;
003: import java.awt.image.*;
004: 
005: //==========================================================
006: // BWFilter (black and white filter) class
007: //==========================================================
008: 
009: class BWFilter extends RGBImageFilter {
010: 
011:  // Constructor
012:  public BWFilter() {
013:   canFilterIndexColorModel = true;
014:  }
015: 
016:  // Return rgb color converted to shade of gray
017:  public int filterRGB(int x, int y, int rgb) {
018:   // Reduce rgb to hue, saturation, brightness elements
019:   Color c = new Color(rgb);
020:   float[] hsbvals = Color.RGBtoHSB(c.getRed(), c.getGreen(),
021:    c.getBlue(), null);
022:   // Return new color value of same brightness but
023:   // with hue and saturation set to zero
024:   return Color.HSBtoRGB(0.0f, 0.0f, hsbvals[2]);
025:  }
026: }
027: 
028: //==========================================================
029: // Applet class
030: //==========================================================
031: 
032: public class Filter extends Applet
033:  implements Runnable {
034: 
035:   // Instance variables
036:  Image pic;             // GIF image producer
037:  int picID;             // Arbitrary image ID
038:  MediaTracker tracker;  // Tracks loading of image
039:  Thread loadingThread;  // Thread for loading image
040:  String filename = "Clown.gif";  // File name
041:  boolean imageReady = false;  // Offscreen image flag
042:  Image bwPic;                 // Offscreen image object
043: 
044:  // Initialize applet
045:  public void init() {
046:   // Size applet window
047:   resize(320, 200);
048:   // Create MediaTracker object
049:   tracker = new MediaTracker(this);
050:   // Start image loading
051:   pic = getImage(getDocumentBase(), filename);
052:   picID = 0;
053:   tracker.addImage(pic, picID);
054:   // Create thread to monitor image loading
055:   loadingThread = new Thread(this);
056:   loadingThread.start();
057:  }
058: 
059:  // Run loading thread
060:  // Allows other processes to run while loading
061:  // the image data
062:  public void run() {
063:   try {
064:    tracker.waitForID(picID);
065:    if (tracker.checkID(picID, true)) {
066:     // Create offscreen image using loaded GIF
067:     // file filtered by our BWFilter class
068:     ImageProducer picSource = pic.getSource();
069:     BWFilter bwFilter = new BWFilter();
070:     bwPic = createImage(new 
071:      FilteredImageSource(picSource, bwFilter));
072:     imageReady = true;
073:    }
074:   } catch (InterruptedException ie) {
075:    return;
076:   }
077:   repaint();  // Cause paint() to draw loaded image
078:  }
079: 
080:  // Paint window contents
081:  // Displays loading or error message until
082:  // image is ready, then shows image
083:  public void paint(Graphics g) {
084:   if (tracker.isErrorID(picID))
085:    g.drawString("Error loading " + filename, 10, 20);
086:   else if (tracker.checkID(picID) && imageReady)
087:    g.drawImage(bwPic, 0, 0, this);  // Show offscreen image
088:   else
089:    g.drawString("Loading " + filename, 10, 20);
090:  }
091: }
Return to top

Listing 23-7 SwingPic/SwingPic.java Page 546

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class SwingPic extends JFrame {
006: 
007:  // Picture file name
008:  protected String filename = "AS17-148-22721.jpg";
009:  protected ImageIcon image;
010: 
011:  // Constructor
012:  public SwingPic() {
013: 
014:   // Select local system look and feel
015:   try {
016:    UIManager.setLookAndFeel(
017:     UIManager.getCrossPlatformLookAndFeelClassName());
018:   } catch (Exception e) { }
019: 
020:   // End program when window closes
021:   addWindowListener(new WindowAdapter() {
022:    public void windowClosing(WindowEvent e) {
023:     System.exit(0);
024:    }
025:   });
026: 
027:   // Load image from file
028:   image = new ImageIcon(filename);
029:   int height = image.getIconHeight();
030:   int width = image.getIconWidth();
031: 
032:   // Create a label to hold the image as an icon
033:   JLabel labeledPic = new JLabel(image, JLabel.CENTER);
034:   labeledPic.setText(filename);
035: 
036:   // Create a scroller to hold the labeled image
037:   JScrollPane scroller = new JScrollPane(labeledPic);  
038:   scroller.setPreferredSize(new Dimension(height, width));
039: 
040:   // Add the scroller to the frame's content layer  
041:   Container content = getContentPane();
042:   content.add(scroller);
043:   setSize(width, height);  // Sets window's initial size
044:  }
045: 
046:  public static void main(String[] args) {
047:   SwingPic app = new SwingPic();
048:   app.setTitle("Swing Picture Demonstration");
049:   app.show();
050:  }
051: }
Return to top

Listing 23-8 Animation/Animation.java Page 547

Return to top
001: import java.applet.*;
002: import java.awt.*;
003: 
004: public class Animation extends Applet 
005:  implements Runnable {
006: 
007:  // Thread for loading and displaying images
008:  Thread animThread = null;
009: 
010:  private final int NUM_IMAGES = 10; // Number of image files
011:  private Image images[];            // Array of images
012:  private int currImage;             // Index of current image
013:  private int imgWidth  = 0;         // Width of all images
014:  private int imgHeight = 0;         // Height of all images
015:  private boolean allLoaded = false; // true = all loaded
016:  private MediaTracker tracker;      // Tracks image loading
017:  private int width, height;         // Applet width and height
018: 
019:  // Initialize applet
020:  public void init() {
021:   width = 320;
022:   height = 240;
023:   resize(width, height);
024:   // Create MediaTracker object. The string is
025:   // for creating the image filenames.
026:   tracker = new MediaTracker(this);
027:   String strImage;
028:   // Load all images. Method getImage() returns immediately
029:   // and all images are NOT actually loaded into memory
030:   // by this loop.
031:   images = new Image[NUM_IMAGES];  // Create image array
032:   for (int i = 1; i <= NUM_IMAGES; i++) {
033:    strImage = "images/img00" + ((i < 10) ? "0" : "") 
034:     + i + ".gif";
035:    images[i-1] = getImage(getDocumentBase(), 
036:     strImage);
037:    tracker.addImage(images[i-1], 0);
038:   }
039:  }
040: 
041:  // Paint window contents
042:  public void paint(Graphics g)
043:  {
044:   // Draw current image
045:   if (allLoaded) {
046:    g.drawImage(images[currImage],
047:     (width - imgWidth) / 2,
048:     (height - imgHeight) / 2, null);
049:   }
050:  }
051: 
052:  // Create and start animation thread
053:  public void start() {
054:   if (animThread == null) {
055:    animThread = new Thread(this);
056:    animThread.start();
057:   }
058:  }
059: 
060:  // Run image load and display thread
061:  public void run() {
062:   // Load images if not already done
063:   if (!allLoaded) {
064:    showStatus("Loading images...");
065:    // Wait for images to be loaded
066:    // Other processes continue to run normally
067:    try  {
068:     tracker.waitForAll();
069:    }
070:    catch (InterruptedException e) {
071:     stop();  // Stop thread if interrupted
072:     return;  // Abort loading process
073:    }
074:    // If all images are not loaded by this point, 
075:    // something is wrong and we display an error 
076:    // message.
077:    if (tracker.isErrorAny()) {
078:     showStatus("Error loading images!");
079:     stop();
080:     return;
081:    }
082:    
083:    // All images are loaded. Set the loaded flag
084:    // and prepare image size variables
085:    allLoaded = true;
086:    imgWidth  = images[0].getWidth(this);
087:    imgHeight = images[0].getHeight(this);
088:   }
089:   
090:   // Loop endlessly so animation repeats
091:   // User ends loop by leaving the page or exiting
092:   // the browser.
093:   showStatus("Displaying animation");
094:   while (true) {
095:    try {
096:     repaint();
097:     currImage++;
098:     if (currImage == NUM_IMAGES)
099:      currImage = 0;
100:     Thread.sleep(50);  // Controls animation speed
101:    }
102:    catch (InterruptedException e) {
103:     stop();
104:    }
105:   }  // end of while statement
106:  }  // end of run() method
107: }
Return to top