Page 190 - The Definitive Guide to Building Java Robots
P. 190

Preston_5564C06.fm  Page 171  Friday, September 23, 2005  5:13 AM



                                                                                   CHAPTER 6  ■  VISION  171



                            public void paint(Graphics g) {
                                if (image != null) {
                                    // in case image resizes background is black
                                    g.setColor(Color.BLACK);
                                    g.fillRect(0,0,this.getWidth(),getHeight());
                                    g.drawImage(image, 0, 0, this);
                                }
                            }
                        }
                            Now that I have a canvas to work with, it’s time to create my ImageViewer class. This class
                        has a single field, currentImage of type BufferedImage. There are two constructors, one taking
                        a BufferedImage as a parameter, and the other taking a filename. In the second constructor to
                        get a JPEG file, I open a FileInputStream, then pass this object to the JPEGImageDecoder, then
                        call the decodeAsBufferedImage() method setting the currentImage. Once its construction is
                        finished, I call init().
                            In the init() method, I get the size of the image, and then construct an ImagePanel with
                        those dimensions. Next, I set the size of the window with enough room for the borders and title
                        bar. Once sized, I add the ImagePanel to the content pane of the frame, make it visible, and
                        then set the image into the ImagePanel. See Example 6-5 and Figure 6-3.


































                        Figure 6-3. The ImageViewer









                   97022d2480fe4a63cfdfa123a6e70098
   185   186   187   188   189   190   191   192   193   194   195