/** * From http://stackoverflow.com/questions/9370592/i-am-looking-for-a-good-example-of-adding-an-image-to-an-applet/9370871#9370871 */ package exampleLab4_ImagePanel; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; @SuppressWarnings("serial") class ImagePanel extends JPanel { private BufferedImage img; public ImagePanel(BufferedImage img) { this.img = img; setPreferredSize(new Dimension(img.getWidth(), img.getHeight())); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (img != null) { // g.drawImage(img, 0, 0, this); // corrected // thiswidth/imgwidth > thisheight/imgheight : // more scaling required in width direction to meet edge, // so scale in height direction to match edge. if(this.getWidth()*img.getHeight() > img.getWidth() * this.getHeight()) { g.drawImage(img, 0, 0, (this.getHeight()*img.getWidth())/img.getHeight(), this.getHeight(), this); } else { g.drawImage(img, 0, 0, this.getWidth(), (this.getWidth()*img.getHeight())/img.getWidth(), this); } } } }