Advertisement
Guest User

Class Image Panel

a guest
Dec 15th, 2019
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. import java.awt.*;  
  2.  import javax.swing.*;  
  3.  import java.awt.image.*;  
  4.  
  5.  public class ImagePanel extends JComponent  
  6.  {  
  7.    // The current width and height of this panel  
  8.    private int width, height;  
  9.    // An internal image buffer that is used for painting. For  
  10.    // actual display, this image buffer is then copied to screen.  
  11.    private OFImage panelImage;  
  12.    /**  
  13.     * Create a new, empty ImagePanel.  
  14.     */  
  15.    public ImagePanel()  
  16.    {  
  17.      width = 360;  // arbitrary size for empty panel  
  18.      height = 240;  
  19.      panelImage = null;  
  20.    }  
  21.    /**  
  22.     * Set the image that this panel should show.  
  23.     *  
  24.     * @param image The image to be displayed.  
  25.     */  
  26.    public void setImage(OFImage image)  
  27.    {  
  28.      if(image != null) {  
  29.        width = image.getWidth();  
  30.        height = image.getHeight();  
  31.        panelImage = image;  
  32.        repaint();  
  33.      }  
  34.    }  
  35.    /**  
  36.     * Clear the image on this panel.  
  37.     */  
  38.    public void clearImage()  
  39.    {  
  40.      Graphics imageGraphics = panelImage.getGraphics();  
  41.      imageGraphics.setColor(Color.LIGHT_GRAY);  
  42.      imageGraphics.fillRect(0, 0, width, height);  
  43.      repaint();  
  44.    }  
  45.    // The following methods are redefinitions of methods  
  46.    // inherited from superclasses.  
  47.    /**  
  48.     * Tell the layout manager how big we would like to be.  
  49.     * (This method gets called by layout managers for placing  
  50.     * the components.)  
  51.     *  
  52.     * @return The preferred dimension for this component.  
  53.     */  
  54.    public Dimension getPreferredSize()  
  55.    {  
  56.      return new Dimension(width, height);  
  57.    }  
  58.    /**  
  59.     * This component needs to be redisplayed. Copy the internal image  
  60.     * to screen. (This method gets called by the Swing screen painter  
  61.     * every time it want this component displayed.)  
  62.     *  
  63.     * @param g The graphics context that can be used to draw on this component.  
  64.     */  
  65.    public void paintComponent(Graphics g)  
  66.    {  
  67.      Dimension size = getSize();  
  68.      g.clearRect(0, 0, size.width, size.height);  
  69.      if(panelImage != null) {  
  70.        g.drawImage(panelImage, 0, 0, null);  
  71.      }  
  72.    }  
  73.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement