Advertisement
obernardovieira

Image resized on JPanel

Jan 16th, 2017
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. //thanks to
  2. //http://stackoverflow.com/questions/22162398/how-to-set-a-background-picture-in-jpanel
  3. //and a little edition
  4.  
  5.  
  6. //PicPanel.java
  7.  
  8.  
  9. import java.awt.Dimension;
  10. import java.awt.Graphics;
  11. import java.awt.image.BufferedImage;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import javax.imageio.ImageIO;
  15. import javax.swing.JPanel;
  16.  
  17. /**
  18.  *
  19.  * @author user
  20.  */
  21. public class PicPanel extends JPanel
  22. {
  23.     private BufferedImage image;
  24.     private int jw, jh;
  25.     public PicPanel(String fname, int image_width, int image_height,
  26.             int jpanel_width, int jpanel_height){
  27.        
  28.         setBounds(0,0,image_width,image_height);
  29.         jw = jpanel_width;
  30.         jh = jpanel_height;
  31.        
  32.         try
  33.         {
  34.             image = ImageIO.read(new File(fname));
  35.         }
  36.         catch (IOException ioe)
  37.         {
  38.             System.out.println(ioe.toString());
  39.             System.out.println("Could not read in the pic");
  40.         }
  41.     }
  42.     @Override
  43.     public void paintComponent(Graphics g)
  44.     {
  45.         super.paintComponent(g);
  46.         g.drawImage(image,0,0,jw,jh,this);
  47.     }
  48. }
  49.  
  50.  
  51.  
  52.  
  53.  
  54. //anywhere on code
  55.  
  56. PicPanel mainPanel = new PicPanel("disk2.png", 256, 256, 180, 180); //image , image width, image height, jpanel width, jpanel height
  57. add(mainPanel);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement