Image Frame Example


import javax.swing.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
import java.awt.event.*;
//panel used to draw image on

class ImagePanel extends JPanel
{
//path of image
private String path;
//image object
private Image img;
public ImagePanel(String path) throws IOException
{
//save path
this.path = path;
//load image
img = ImageIO.read(new File(path));
}
//override paint method of panel
public void paint(Graphics g)
{
//draw the image
if( img != null)
g.drawImage(img,0,0, this);
}
}

//example of using image panel
public class ImageFrame implements ActionListener
{
JFrame f = new JFrame();
JButton btn=new JButton("Open");
ImagePanel panel=null;

public ImageFrame()
{

f.setLayout(null);
btn.addActionListener(this);
//f.getContentPane().add(panel);
btn.setBounds(10,10,20,20);

f.add(btn);

f.setSize(200,200);
//f.setBounds(0,0,600,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println ( "inside");
JFileChooser chooser = new JFileChooser();
System.out.println ( "inside2");
chooser.showOpenDialog(f);
try
{
panel = new ImagePanel( chooser.getSelectedFile().getPath() );
}
catch(Exception e)
{
System.out.println ( "Please verify that you selected a valid image file");
}
panel.setBounds(10,25,100,100);
f.add(panel);

}

public static void main(String[] args) throws IOException
{

new ImageFrame();

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s