viernes, 8 de abril de 2011

[Java] First Steps: Load a PNG/JPG image in a JFrame

Hi, this is one simple code for load and show an image inside a JFrame, using a BufferedImage to load image data from a specific local path (could be a URL if you prefer).

1.- Create a BufferedImage object.
2.- Read the image file for a specific path
3.- Draw the image in the screen using "paint()" method.

That's it!
package mx.gcross.samples;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

* @author Rene Cruz - G-Cross Studio 2011
public class MyWindow extends JFrame {

//Object for image
private BufferedImage background;

public MyWindow() {

setSize(480, 320); //set window dimension 480x320px
setVisible(true); //make window visible

public void loadImages() {
try {
//path for image file
String path = "images/background.png";
background = File(path));
} catch (IOException ex) {

public void paint(Graphics g) {
//draw the bufferedImage object
g.drawImage(background, 0, 0, this);

public static void main(String[] args) {
new MyWindow();

Test the code and comment, thanks!.

If you prefer the complete code source and resources in a Netbeans project, Download It Here!

No hay comentarios:

Publicar un comentario