import javax.swing.*;
import java.awt.*;
public class ImageTest extends JApplet {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// public void init() is called by the applet viewer/java virtual machine/browser
// as one of the first methods of the JApplet
public void init() {
// Use a simple flow layout:
this.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
// Add the JPanel with the image painted on it to the applet - make it
// half the height and the full width of the applet:
this.getContentPane().add(imagePanel("image.jpg",this.getWidth(),(this.getHeight()/2)));
// Add a JLabel which contains an ImageIcon of the image:
this.getContentPane().add(new JLabel(new ImageIcon(this.getClass().getResource("image.jpg"))));
// Repaint the applet so they show up:
this.getContentPane().repaint();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - \\
// Instance Variables \\
// - - - - - - - - - - - \\
Image img; // variable referenced to the image passed to the method:
int width; // the width of the JPanel, which is passed to the function:
int height; // the height of the JPanel, which is passed to the function:
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// imagePanel returns a JPanel of size w x h with the image from the filename passed
// to it painted on it.
// The advantage to having this as a method or even a separate class is that
// you don't have to copy-paste code every time you need an image.
// Precondition: this supports method getClass(), this is an ImageObserver
// Postcondition: returns a JPanel with the image from a file contained in
// the jar file painted on it of size w x h
private JPanel imagePanel(String filename, int w, int h) {
// Save the local variables to instance variables so the paint method can
// access them
width = w;
height = h;
// actually extract the image from the jar file, referenced by "img"
img = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(filename));
// create the JPanel that will be returned...
JPanel j = new JPanel() {
// override the paint method to include drawing the image on the JPanel
public void paint(Graphics g) {
// draw the image on the Jpanel
g.drawImage(img, 0, 0, width, height, this);
}
};
// Set the JPanel's size to the desired dimentions
j.setPreferredSize(new Dimension(width, height));
// finally, return the JPanel to whatever called this method...
return j;
}
}