To insert an image in a Java AWT (Abstract Window Toolkit) application, you can use the Image
class of the java.awt
package. The Image
class represents an image in memory, and it provides methods for loading and drawing images on a window or component.
Here is an example of how to insert an image in a Java AWT application using the Image
class:
import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class ImageExample extends Frame { Image image; public ImageExample() { image = Toolkit.getDefaultToolkit().getImage("image.png"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void paint(Graphics g) { g.drawImage(image, 50, 50, this); } public static void main(String[] args) { ImageExample frame = new ImageExample(); frame.setSize(200, 200); frame.setVisible(true); } }
In this example, the ImageExample
class extends the Frame
class and displays an image in a window. It defines an image
field of type Image
and loads the image using the getImage()
method of the Toolkit
class. The getImage()
method takes the path of the image file as an argument and returns an Image
object representing the image.
The paint()
method of the Frame
class is called whenever the window needs to be repainted, and it receives a Graphics
object as an argument. The drawImage()
method of the Graphics
class is used to draw the image on the window at the specified location (50, 50).
To run the example, make sure to include the image file "image.png" in the same directory as the Java class file.