Home Tutorial Java Swing Display Image on JDesktopPane

 
 

Display Image on JDesktopPane
Posted on: December 1, 2009 at 12:00 AM
In this section, you will learn how to retrieve an image from  the database and display it on the JDesktopPane.

Display Image on JDesktopPane

In this section, you will learn how to retrieve an image from  the database and display it on the JDesktopPane. You can see in the given example, we have retrieved an image in the form of bytes and the method createImage() get these bytes and allowed the retrieved image to be displayed on the JDesktoPane.

Here is the code:

import java.sql.*;
import java.awt.*;
import javax.swing.*;

public class RetrieveImage {
	public static void main(String argv[]) {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/test", "root", "root");
			Statement stmt = con.createStatement();
			ResultSet rs = stmt
					.executeQuery("select image from image where image_id='3'");
			byte[] bytes = null;
			if (rs.next()) {
				bytes = rs.getBytes(1);
			}
			rs.close();
			stmt.close();
			con.close();
			if (bytes != null) {
				JFrame f = new JFrame();
				f.setTitle("Display Image From database");
				Image image = f.getToolkit().createImage(bytes);
				f.getContentPane().add(new Pane(image));
				f.setSize(300, 100);
				f.setVisible(true);
			}
		} catch (Exception e) {
		}
	}
}

class Pane extends JDesktopPane {
	private Image image;

	public Pane(Image image) {
		this.image = image;
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(image, 0, 0, this);
	}
}

Output:

Related Tags for Display Image on JDesktopPane:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.