View Javadoc

1   /**
2    * 
3    */
4   package sk.stuba.fiit.foo07.genex.gui;
5   
6   import java.awt.Color;
7   import java.awt.Dimension;
8   import java.awt.Graphics;
9   import java.awt.Image;
10  import java.awt.MediaTracker;
11  
12  import javax.swing.ImageIcon;
13  import javax.swing.JPanel;
14  
15  /**
16   * @author _mizu_
17   * 
18   */
19  public class PictureComponent extends JPanel {
20  
21      /**
22       * 
23       */
24      private static final long serialVersionUID = 216961397493029305L;
25      private Image orig;
26      private Image scaled;
27      private Image actual;
28      private boolean isScaled = true;
29  
30      public void setImage(byte[] content) {
31          MediaTracker mt = new MediaTracker(this);
32  
33          orig = new ImageIcon(content).getImage();
34          float w = getMinimumSize().width;
35          float h = getMinimumSize().height;
36          float ow = orig.getWidth(null);
37          float oh = orig.getHeight(null);
38          float faktor;
39  
40          faktor = ow / oh;
41          if (faktor > 1.0)
42              h /= faktor;
43          else
44              w *= faktor;
45  
46          scaled = orig.getScaledInstance(Math.round(w), Math.round(h),
47                  Image.SCALE_SMOOTH);
48  
49          mt.addImage(orig, 0);
50          mt.addImage(scaled, 1);
51          try {
52              mt.waitForAll();
53          } catch (Exception e) {
54          }
55  
56          setActualSize();
57      }
58  
59      public void setScaled(boolean val) {
60          isScaled = val;
61          setActualSize();
62      }
63  
64      private void setActualSize() {
65          if (isScaled)
66              actual = scaled;
67          else
68              actual = orig;
69  
70          if (actual != null)
71              setPreferredSize(new Dimension(actual.getWidth(null), actual
72                      .getHeight(null)));
73          repaint();
74      }
75  
76      @Override
77      public void paintComponent(Graphics g) {
78          g.setColor(Color.BLACK);
79          g.fillRect(0, 0, getBounds().width, getBounds().height);
80          if (actual != null) {
81              g.drawImage(actual, 0, 0, null);
82              g.setColor(Color.RED);
83              String toDraw = "" + orig.getWidth(null) + "x"
84                      + orig.getHeight(null);
85              g.drawString(toDraw, 3, 12);
86          }
87      }
88  }