aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes how to insert an image using swings in java? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "how to insert an image using swings in java?" Watch "how to insert an image using swings in java?" New topic
Author

how to insert an image using swings in java?

Ruchi Yadav
Greenhorn

Joined: Aug 22, 2009
Posts: 7
hello .....i need to insert an image using swings in my project...but there is an error.....
the code is as shown below :-


import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;



class ImageFrame extends JFrame
{
ImageFrame(String s)
{
setSize(800,600);
setTitle("imgtest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
ImagePanel panel=new ImagePanel();
add(panel,BorderLayout.CENTER);
}
}
class ImagePanel extends JPanel
{
Image image;
ImagePanel()
{
try
{
image=ImageIO.read(new File("SunSet.jpg"));
}
catch(IOException e)
{
e.printStackTrace();
}


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



}

}



public class image
{
/** Creates a new instance of image */
public image()
{
}
public static void main(String[] args)
{
ImageFrame frame=new ImageFrame("Image");
}

}
adeeb alexander
Ranch Hand

Joined: May 29, 2008
Posts: 268
Ruchi please use code tags next time you post your code. The code below shows how to add image to the panel. May help you out.



You just override the JPanels paint method. The above code sets the image totally as the background. If your requirement is to set the image as just a icon, then you can use the JLabel, and the component to the panel.
John Eipe
Ranch Hand

Joined: May 23, 2008
Posts: 215
You can either add the Image as a Label or as Background. Do you get any runtime errors?

Regards,
John Eipe

www.cs-repository.info
Ruchi Yadav
Greenhorn

Joined: Aug 22, 2009
Posts: 7
i dint got any kinda runtime error but my frame ws displayed without the picture and the error ws in paintComponent method as i mentioned it in my code...
well i'll try the newer method.......thanks
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
your error would be that you have paintComponent() inside of the ImagePanel()'s constructor.

even if you fix that, the image won't show unless you force a repaint (minimize then maximize or drag frame wider etc),
as you've made the frame visible before adding the imagePanel
Ruchi Yadav
Greenhorn

Joined: Aug 22, 2009
Posts: 7
hey adeeb i tried your method........but its unable to find symbol Login....
would you please tell me what's the package of Login?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to insert an image using swings in java?