home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch07 / ImageSize.java < prev    next >
Encoding:
Java Source  |  1998-12-14  |  1.8 KB  |  84 lines

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.applet.Applet;
  4.  
  5. /*
  6.  * an applet that allows an image to be resized
  7.  */
  8. public class ImageSize extends Applet implements ActionListener {
  9.  
  10. /*
  11.  * the image to draw
  12.  */
  13. Image img;
  14. Button btnSmaller;
  15. Button btnBigger;
  16.  
  17. /*
  18.  * the current width and height of the image
  19.  */
  20. double width, height;
  21.  
  22. /*
  23.  * the image size scale factor
  24.  */
  25. double scale = 1.0;
  26.  
  27.  
  28. /*
  29.  * called when the applet is loaded or reloaded
  30.  */
  31. public void init() {
  32.  
  33.     setLayout(new BorderLayout());
  34.     Panel p = new Panel ();
  35.     add("South", p);
  36.     btnSmaller = new Button("Smaller");
  37.     p.add (btnSmaller);
  38.       btnBigger = new Button("Bigger");
  39.     p.add (btnBigger);
  40.     btnSmaller.addActionListener(this);
  41.        btnBigger.addActionListener(this);
  42.  
  43.     MediaTracker tracker = new MediaTracker (this); 
  44.  
  45.     img = getImage (getDocumentBase(), "T1.gif");
  46.     tracker.addImage (img, 0);
  47.     showStatus ("Getting image: T1.gif");
  48.     try {
  49.         tracker.waitForID (0);
  50.     } catch (InterruptedException e) { }
  51.     width = img.getWidth (this);
  52.     height = img.getHeight (this);
  53. }
  54.  
  55. public void paint (Graphics g) {
  56.     double w, h;
  57.  
  58.  
  59.     w = scale * width;
  60.     h = scale * height;
  61.  
  62.     // if we don't have the size yet, we shouldn't draw
  63.     if (w < 0 || h < 0) { w=75; h=75; } //return;
  64.  
  65.     // explicitly specify width (w) and height (h)
  66.     g.drawImage (img, 10, 10, (int) w, (int) h, this);
  67. }
  68. public void actionPerformed(ActionEvent evt)
  69. {
  70.     Object object1 = evt.getSource();
  71.     if (object1 == btnSmaller)
  72.     {
  73.         scale *= 0.9;    // make it 10% smaller
  74.         repaint ();
  75.     }
  76.     if (object1 == btnBigger)
  77.     {
  78.         scale *= 1.1;    // make it 10% bigger
  79.         repaint ();
  80.     }
  81. }
  82.  
  83. }
  84.