• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to insert an image using swings in java?

 
Ruchi Yadav
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 215
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can either add the Image as a Label or as Background. Do you get any runtime errors?

Regards,
John Eipe
 
Ruchi Yadav
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey adeeb i tried your method........but its unable to find symbol Login....
would you please tell me what's the package of Login?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic