Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/watsonnet/jcap/ImagePanel.java


1   package com.watsonnet.jcap;
2   
3   // java:
4   import java.awt.*;
5   import java.awt.image.*;
6   import java.awt.event.*;
7   import java.io.*;
8   import java.net.*;
9   import java.util.Vector;
10  import java.util.Date;
11  import java.net.URL;
12  import java.util.Arrays;
13  
14  // swing:
15  import javax.swing.*;
16  import javax.swing.event.*;
17  
18  public class ImagePanel extends JPanel {
19    private Image image = null;
20    private boolean loading = false;
21    
22    // set the image
23    public void setImage(Image img) {
24      image = null;
25      
26      image = img;
27      
28      // Set loading to true so that we always show the "Loading..." text
29      // even if the image is loaded very quickly.
30      if (image != null) {
31        loading = true;
32      }
33      
34      repaint();
35    }
36    
37    // return the image
38    public Image getImage() {
39      return(image);
40    }
41    
42    public void paintComponent(Graphics g) {
43      super.paintComponent(g);
44      
45      // draw this first.  if the image loads fast enough then both of these
46      // draws will happen in the same call.  if that happens and these are
47      // in the wrong order then you end up with a picture with "Loading..."
48      // written on it.
49      if (loading) {
50        g.drawString("Loading...", this.getWidth()/2, this.getHeight()/2);
51      }
52      
53      // draw the image, scaled
54      if (image != null) {
55        int w, h, sw, sh;
56        float ratio;
57        
58        w = image.getWidth(this);
59        h = image.getHeight(this);
60        ratio = (float)w/(float)h;
61        
62        if (w > this.getWidth()) {
63          w = this.getWidth();
64          h = (int)(w/ratio);
65        }
66        if (h > this.getHeight()) {
67          h = this.getHeight();
68          w = (int)(h*ratio);
69        }
70        
71        // centering coordinates
72        sw = (Math.abs(this.getWidth())-w)/2;
73        sh = (Math.abs(this.getHeight())-h)/2;
74        
75        // draw
76        g.drawImage(image, sw, sh, w, h, this);
77      }
78    }
79    
80    // wait for the image to be completely loaded then repaint the panel
81    public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
82      if ((infoflags & ALLBITS) == ALLBITS) {
83        loading = false;
84        repaint();
85      } else if ((infoflags & ABORT) == ABORT) {
86        loading = false;
87        repaint();
88      } else {
89        loading = true;
90      }
91      return(loading);
92    }
93  }
94