Draw an Image to a JPanel


Here's simple Java code to make image or photo preview using JPanel.
package myjavaexample; 
 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.WindowConstants; 
 
public class MyJavaExample extends JFrame 
{ 
    private BufferedImage image; 
    public void openImage() 
    { 
        try{ 
            image = ImageIO.read(new File("C:\\Users\\Edugame\\Pictures\\dev_icon3.png")); 
        }catch(IOException e){} 
 
        JPanel pane = new JPanel() { 
            protected void paintComponent(Graphics g) { 
                super.paintComponent(g); 
                g.drawImage(image, 0, 0, null); 
            } 
        }; 
        pane.setPreferredSize(new Dimension(image.getWidth(),image.getHeight())); 
        add(pane); 

        setTitle("Simple Image Preview"); 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
        setSize(200,200); 
        pack(); 
        setVisible(true); 
    } 

    public static void main(String[] args) { 
        MyJavaExample mainwin=new MyJavaExample(); 
        mainwin.openImage(); 
    } 
} 

Comments



Popular posts from this blog

Simple Java Code HTML Highlighter

How to Use Extends and Implements

Fibonacci Algorithm in Java Array