Home Tutorial Java Swing Display Image on JDesktopPane

 
 

Share on Google+Share on Google+
Display Image on JDesktopPane
Posted on: December 1, 2009 at 12:00 AM
Advertisement
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:

Advertisement

Related Tags for Display Image on JDesktopPane:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 1, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com