001    package org.springframework.richclient.widget;
002    
003    import org.springframework.core.io.Resource;
004    
005    import javax.swing.*;
006    import java.io.IOException;
007    
008    /**
009     * ImageViewingWidget generates a component to view an image.
010     *
011     * {@inheritDoc}
012     *
013     * @see #setImage(javax.swing.ImageIcon)
014     * @see #setImage(org.springframework.core.io.Resource)
015     */
016    public class ImageViewWidget extends AbstractWidget
017    {
018        private JLabel imageHolder;
019        private JComponent mainComponent;
020        private boolean hasContent;
021    
022        public ImageViewWidget()
023        {
024            this.imageHolder = new JLabel();
025    
026            // below is a small lie to make sure we provide a blank control in case
027            // people create us without ready content
028            this.hasContent = true;
029    
030            this.mainComponent = imageHolder;
031        }
032    
033        public ImageViewWidget(Resource resource)
034        {
035            this();
036            setImage(resource);
037        }
038    
039        public ImageViewWidget(ImageIcon image)
040        {
041            this();
042            setImage(image);
043        }
044    
045        /**
046         * Sets the image content of the widget based on a resource
047         *
048         * @param resource
049         *            points to a image resource
050         */
051        public void setImage(Resource resource)
052        {
053            ImageIcon image = null;
054            if (resource != null && resource.exists())
055            {
056                try
057                {
058                    image = new ImageIcon(resource.getURL());
059                }
060                catch (IOException e)
061                {
062                    logger.warn("Error reading resource: " + resource);
063                    throw new RuntimeException("Error reading resource " + resource, e);
064                }
065            }
066            setImage(image);
067        }
068    
069        /**
070         * Sets the image content based on an ImageIcon
071         *
072         * @param image
073         *            The image icon to be shown
074         */
075        public void setImage(ImageIcon image)
076        {
077            this.imageHolder.setIcon(image);
078            this.hasContent = (image != null);
079        }
080    
081        public JComponent getComponent()
082        {
083            return this.hasContent ? this.mainComponent : new JPanel();
084        }
085    }