This discussion is archived
2 Replies Latest reply: Jun 5, 2010 10:39 AM by 800414 RSS

Add Image to Frame?

843807 Newbie
Currently Being Moderated
I'm having trouble adding an Image to a Frame in Java. I don't want to refactor my code to use swing; I'm a little on a deadline. Is there any way to add an Image to a Frame, in the same way that Buttons and Checkboxes can be added?
  • 1. Re: Add Image to Frame?
    843807 Newbie
    Currently Being Moderated
    You can put an image in a panel through an override, then add the panel to the frame.
  • 2. Re: Add Image to Frame?
    800414 Newbie
    Currently Being Moderated
    try this

    import java.awt.Canvas;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    
    public class ImageViewer  extends Canvas{
      
      private Image m_img = null;
    
      public ImageViewer(){}
    
      public ImageViewer(File imageFile){
        setImage(imageFile);
      }
    
      public ImageViewer(Image img){
        setImage(img);
      }
    
      public void setImage(File imageFile){
        if(imageFile == null){
          throw new IllegalArgumentException("File image cant be null");
        }
        try {
         //you can use toolkit to load image , ImageIO is batter 
          Image img = ImageIO.read(imageFile);
          setImage(img);
        } catch (IOException e) {
          e.printStackTrace();
        }
      
      }
     
      public void setImage(Image img){
        m_img = img;
        if(m_img != null){
          MediaTracker tracker = new MediaTracker(this);
          tracker.addImage(m_img, 0);
          try {
            tracker.waitForID(0);
          } catch (Exception waitingError) {
    
          }
        }    
      }
    
      public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D)g;
    
    
        if(m_img != null){
          int width  = getSize().width;
          int height = getSize().height;
          
          ///YOU CAN SCALE YOU IMAGE HERE
    //      m_img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
    
          g2d.drawImage(m_img ,0 ,0 ,width ,height ,this);
        }
    
      }
    
    }