Putting an image into a JFrame or a JPanel

Hello everybody,
I'd like to know how to put an image (a real one, not a small icon we can't see it!) into a JFrame, or a JPanel, or included into a miscellanea element (label, textfield or somethiong else).
Thanks,
Regards
Cedric

Hi Cedric,
If the image format is Jpg or gif, then the best way to insert the image
into the Frame or panel is to use JLabel. You can pass the argument to the file as parameter to JLabel construction.
For other formats, you have the option of using drawimage in paint function of applets.
Hope this helps.
Best Regards,
Chandru

Similar Messages

  • How do you set an image into the background of a JPanel or JFrame?

    How do you set an image into the background of a JPanel or JFrame?

    Something like this, Ive thrown in an ImageIcon on a
    button too for good measure.
    import java.awt.*;
    import javax.swing.*;
    public class JFrameImage extends JFrame {
    public JFrameImage() {
    Container c    = getContentPane();
    JPanel panel = new JPanel(){
                 public void paintComponent(Graphics g)     {
    ImageIcon img = new
    = new ImageIcon("background.jpg");
                      g.drawImage(img.getImage(), 0, 0, null);
                      super.paintComponent(g);
            panel.setOpaque(false);
    ImageIcon icon = new ImageIcon("onButton.jpg");
    JButton button = new JButton(icon);
    panel.add(button);
    c.add(panel);
    public static void main(String[] args) {
    JFrameImage frame = new JFrameImage();
    frame.setSize(200,200);
    frame.setVisible(true);
    Going totally fancy pants
    ImageIcon bigImage = new ImageIcon(bgImage.getImage().getScaledInstance(getWidth(), getHeight(),Image.SCALE_REPLICATE));
    g.drawImage(bigImage.getImage(), 0, 0, this); Will scale the image to the size of the panel
    whereas
    for (int y = 0; y  < getHeight(); y = y + image.getHeight(null))
    for (int x = 0; x< getWidth(); x = x + image.getWidth(null))
    g.drawImage(image, x, y, this); Will give a tiled effect
    Try tiling with an animated gif and bring your processor to a standstill.

  • Putting an image in a JFrame

    I'm trying to paint an image onto a JFrame. Im making a monopoly game and need to paint the board, and repaint it after every turn. I dont know how to put an image onto a JFrame and was wondering if anyone could give me a basic algorithm or code example of how to do this. Thanks.

    Here is the basic algorithm to paint to a JFrame:
    Don't do it!
    Set the preferred size of a JPanel and add the JPanel to the JFrame. Paint to the JPanel by extending the paintComponent method. When you're ready to display, then remember to pack the JFrame and setVisible appropriately.
    You can read about doing this in the Java Tutorial.
    public void paintComponent(Graphics g){ //override in JPanel
      super.paintComponent(g);
      //do what ever you need to do here to draw your graphics.
    }I prefer to do all of my drawing to a BufferedImage and then use drawImage to show the image (off screen rendering):
    public void paintComponent(Graphics g){ //override in JPanel
      g.drawImage(myImage, 0, 0, this);
    }

  • Putting an Image into a Frame

    Hi there,
    Ive created an applet in Java which is basically a square with a boucing ball in it. The problem is i want to put this into a JFrame so i can add other controls. How would i go about this?? I initialise the image in the intialisation... i.e.
    Buffer=createImage(600,600);
    gBuffer=Buffer.getGraphics();
    then i have my paint method as so.
    public void paint(Graphics g)
    gBuffer.setColor(Color.blue);
    gBuffer.fillRect(0,0,size().width,size().height);
    gBuffer.setColor(Color.yellow);
    gBuffer.fillOval(0,0,600,600);
    //Loop through Crabs
    for (int i=0; i<=iNumberofCrabs; i++){
    //Get Home
    if(iCrab.getHasHome()){
    Home phome = iCrab[i].getHome();
    //Paint Home and Crab
    phome.paint(gBuffer);
    iCrab[i].paint(gBuffer);
    g.drawImage (Buffer,20,10, this);
    Any help would be great....
    Regards James

    i would probably do like this....................
    * ImageClass.java
    * Created on February 16, 2006, 1:20 AM
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    * @author hussain
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    public class ImageClass extends JFrame
        jpanel j;
        public ImageClass()
            super("Image Application");
            Container cpane = getContentPane();
            j = new jpanel();
            cpane.add(j);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String args[])
            final JFrame f = new ImageClass();
            f.setBounds(100, 100, 300, 300);
            f.setVisible(true);
    class jpanel extends JPanel
        Image image;
        int i = 0;
        short array[]= null;
        jpanel()
            setBackground(Color.WHITE);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            BufferedImage aImage = gc.createCompatibleImage(200, 200, Transparency.BITMASK);
            image = Toolkit.getDefaultToolkit().getImage("c:\\fatwa.jpg");
            g.drawImage(image, 0,0,this);
    }

  • Putting selected images into an album, without dragging

    Once multiple images have been selected in the library of iphoto2, how can you put them all into an album ?

    If you have numerous photos selected, if you drag one, the rest will come too.

  • How can i load or put an image into array of pixels?

    i am doing my undergraduate project , i am using java , mainly the project works in image manipulating or it is image relevant , few days ago i stucked in a little problem , my problem is that i want to put an image scanned from scanner into array or anything ( that makes me reach my goal which is go to specific locations in the image to gather the pixel colour on that location ) , for my project that's so critical to complete the job so , now am trying buffered image but i think it will be significant if i find another way to help , even it isn't in java i heared that matlab has such tools & libraries to help
    thanks .....
    looking forward to hearing from you guys
    Note : My project is java based .

    Check out the PixelGrabber class: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/PixelGrabber.html
    It's pretty simple to get an array of Color objects - or you could just leave it as an int array - though it can be somewhat slow.
    //img - Your img
    int[] pix=new int[img.getWidth(null)*img.getHeight(null)];
    PixelGrabber grab=new PixelGrabber(img,0,0,img.getWidth(null),img.getHeight(null),pix,0,img.getWidth(null));
    grab.grabPixels();  //Blocks, you could use startGrabbing() for asynchronous stuff
    Color[] colors=new Color[pix.length];
    for(int in1=0;in1<colors.length;in1++){
    colors[in1]=new Color(pix[in1],true);  //Use false to ignore Alpha channel
    }//for
    //Colors now contains a Color object for every pixel in the image//Mind you, I haven't compiled this so there could be errors; but I've used essentially the same code many times with few difficulties.

  • Urgent : how to put an image into database and how to get it from it?

    hi,
    in the database i made a longblob type for image, and in my java code i have the path of the image (String): "C:\............." and i want to put this image in my data base.
    also i want to know how to get the image after put it in the database.
    please help me, it's so urgent.

    This is a way of getting the image out of the database.
    class yourClass{
    private byte[] buff;
    private ByteArrayOutputStream byteArrayOutputStream;
    public yourClass()
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet result = statement.executeQuery("your query");
    while ( result.next()){
    try{
    BufferedInputStream bin = new BufferedInputStream(rs.getBinaryStream("imagecolumn"));
    byteArrayOutputStream = new ByteArrayOutputStream();
    int length = bin.available();
    buff = new byte[length];
    while ( bin.read( buff, 0, length ) != -1 ) {
    byteArrayOutputStream.write( buff, 0, length );
    bin.close();
    catch(Exception e){
    The class about is used to take the image out of the database and store it in an object which is then streamed out through a servlet to display on the jsp page.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    public class ImageServlet extends HttpServlet {
    public void init() throws ServletException {    }
    public void destroy() {    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try
    yourClass pro = (yourClass)request.getSession().getAttribute("object");
    while ( iterator.hasNext() ) {
    pro = ( Product ) iterator.next();
    response.setContentType("image/jpg");
    ByteArrayOutputStream byteArrayOutputStream = pro.getImage();
    response.setContentLength( byteArrayOutputStream.size() );
    response.getOutputStream().write( byteArrayOutputStream.toByteArray() );
    response.getOutputStream().flush();
    return;
    catch (Exception e)
    e.printStackTrace();
    throw new ServletException(e);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    This is a little messy but if you search the forums you will find out more on it. Search for Images and database.

  • Putting an image into a JApplet

    Okay so I've made a logo in Fireworks, saved as a jpg, and now I'm trying to put it on to my JApplet.
    I've tried...
    ImageIcon logo = new ImageIcon("C:\folder1\folder2\image.jpg");
    mainNorth.add(logo);
    but it says illegal escape character compiler error...any ideas? :s

    Aurora88 wrote:
    it still says illegal escape character...:sLet's see:
    1) the complete error message (yes, the whole thing, and please put it between code tags)
    2) an SSCCE -- a small program that compiles and demonstrates your problem. This program will just create a JApplet and try to place an image in a JPanel of the JApplet, it should be enough code to demonstrate your problem and nothing else. For more information, have a look at this:
    http://homepage1.nifty.com/algafield/sscce.html
    Remember, the code must be compilable and runnable for many of us to be able to understand it fully.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
    &#91;/code]

  • How do I put raw images into smart collections?

    I have just created some smart collections, however the CR files were rejected.  Is there a way to include them?  I shoot raw/jpeg, so would like both formats in the collection.
    Thanks.

    I just checked Raw images in smart collections. It just worked like any other JPEG files.If u can view thumbnails of Raw in bridge,as per my assumption,there cannot be any problem in creating smart collection.If u can not view thumbnails u may need to update the bridge to read the particular camera model image.any contradiction will be received in right spirit

  • Putting an image into a jtextpane / problems with ImageIcon and path

    So here is what I am trying to do. I would like to be able to allow the user to add images to a jtextpane which will also contain rtf text.
    My current plan is to have a drag event or some other event run the actual code to place the image in the jtextpane. So my first attempt was just to first write a test program to add an image to a textpane using a hard coded path. The problem is i cant seem to create an imageicon using a canonical path because the image icon constructor wants a relative path(from the docs).
    So i guess the best solution would be to convert the canonical path to a relative path. I have this forum and google many times and found many similar posts but none with a real solution (people just reply, why would you want to do that etc.).
    So i either need to convert the path or if any one has a better suggestion to allow users to add images to the jtextpane. Any suggestions?

    show the path you are trying to use.
    Edited by: JacobsB on Mar 13, 2008 1:11 PM
    and try this
    URL url = getClass().getResource(pathName);
    ImageIcon(url);

  • Loading Images into Applets

    I've been having problems loading an image into an Applet. I've found that when the getImage() call is put into the init() method it loads the image fine, also implementing an imageUpdate call. However, now I'm trying to expand on this by putting it into a button click, it hangs indefinitely while waiting for the image to load.
    Another interesting point I've noticed is that the Canvas subclass ImageSegmentSelector uses a PixelGrabber in its constructor to put the Image into a buffer - when this class is created from the imageUpdate() call, NOT the init() call, the grabPixels() call hangs indefinitely too!!
    Any feedback, please,
    Jonathan Pendrous
    import java.applet.*;
    import java.net.*;
    import jmpendrous.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class XplaneGlobalSceneryDownloader extends Applet implements ActionListener{
    ImageSegmentSelector worldMap;
    Image img;
    URL url;
    int longtitude = 36;
    int latitude = 18;
    boolean imageLoaded;
    TextField t1, t2,t3;
    Label l1,l2,l3;
    Button b1;
    Applet a1;
    public void init() {
    a1 = this;
    l1 = (Label) add(new Label("Number of horizontal sections: "));
    t1 = (TextField) add(new TextField("45",3));
    l2 = (Label) add(new Label("Number of vertical sections: "));
    t2 = (TextField) add(new TextField("45",3));
    l3 = (Label) add(new Label("URL of image file: "));
    t3 = (TextField) add(new TextField("file:///C:/java/work/xplane_project/source/world-landuse.GIF",60));
    b1 = (Button) add(new Button("Load image"));
    b1.addActionListener(this);
    validate();
    // THIS CODE WORKS FINE ...
    /*try { url = new URL("file:///C:/java/work/xplane_project/source/world-landuse.GIF"); }
    catch(MalformedURLException e) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false) { try { Thread.sleep(1000);   } catch(InterruptedException e) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();*/
    //repaint();
    //worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    //repaint();
    public void actionPerformed(ActionEvent e) {
    try { longtitude = Integer.parseInt(t1.getText()); } catch (NumberFormatException ex) {System.exit(0); }
    try { latitude = Integer.parseInt(t2.getText()); } catch (NumberFormatException e2) {System.exit(0); }
    try { url = new URL(t3.getText()); }
    catch(MalformedURLException e3) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false)
    { try { Thread.sleep(1000);   } //KEEPS ON LOOPING
    catch(InterruptedException e4) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(a1, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();
    public boolean imageUpdate(Image i, int flags, int x, int y, int w, int h){
    // THIS NEVER GETS CALLED AT ALL //
    if (((flags & ImageObserver.WIDTH) != 0) && ((flags & ImageObserver.HEIGHT) != 0)) {
    //worldMap = new ImageSegmentSelector(this, i, longtitude, latitude);
    //add(worldMap);
    //validate();
    //repaint();
    imageLoaded = true;
    return false;
    return true;
    }

    Sorry, thought this had been lost.
    You can load a file if the applet itself is run from the local filesystem - it loads it fine from the init(), but not otherwise. But I haven't got the applet to run from a browser yet without crashing (it's OK in the IDE debugger), so that's the next step.

  • Inserting image in a jframe

    is it possible to insert an image into a jframe?
    as far as i noe, i can insert a jlabel, and etc. but how about an image?
    if it is possible, can someone please teach me how to do it and post me the codes.
    Thank you.

    You could use g.drawImage, but the simplest solution would be to add the image to a JLabel and add the JLabel to the JFrame.
    JLabel myLabel = new JLabel(new ImageIcon("yourimage.gif"));
    getContentPane().add(myLabel);

  • Copy blob images into ORDIMAGE column

    Hi
    I actually have a table (TABLE1) with a blob column. Images are Stored in this table. In order to user Intermedia Image (scale method), I need to put this images into a table (TABLE2) with an ORDIMAGE type column.
    TABLE1
    ID NUMBER
    PHOTO BLOB
    TABLE2
    ID NUMBER
    PHOTO ORDSYS.ORDIMAGE
    I'm able to insert data in the new table, but the properties of the ordimage columns are not set properly and I get IMG-704 when I try to use the setProperties method of the Ordimage columns.
    Can anyone Help ?
    Thanks
    Olivier GIBERT
    null

    Here is the proc I Use to transfer from blob table named photo to ORDIMAGE table named PHOTO_TEST
    procedure blob_to_ordimage is
    cursor get_blob_cur is
    select numphoto
    , photo
    from photo
    where rownum<50;
    localImage ordsys.ordimage;
    begin
    delete from photo_test;
    FOR get_blob_rec IN get_blob_cur
    LOOP
    localImage := ordsys.ordimage(ordsys.ordsource
    (get_blob_rec.photo,null,null,
    null,null,null),null,null,null,null,null,null,null);
    localImage.setLocal();
    insert
    into photo_test
    ( numphoto
    , photo)
    values
    ( get_blob_rec.numphoto
    , localImage);
    END LOOP;
    commit;
    end;
    this proc works fine but image properties are unset.
    If I add the following command :
    localImage.setProperties;
    after the Image.setLocal, I get ORA-704.
    Can anyone help ???
    null

  • Copy an image into system clipboard takes too much memory

    Our Swing application copies a java.awt.BufferedImage into the system clipboard. Our image has a size of 1024x768 pixels and a depth of 24 bits per pixel.
    The copy from the image to the system clipboard works, but is very slow and takes too much memory. Before the copy, java.exe uses about 30 MB. After the copy, it uses about 90 MB! However, a 1024x768x3 image should consume only 2,4 MB.
    We did some debugging and it seems the AWT library does several copies of our original image in order to copy it in the system clipboard. I guess that each of these copies takes a lot of memory (probably because of a different format from the original image) and is not immediately garbage collected.
    This is a big issue for our application because the JVM throws an OutOfMemoryError when we try to copy a new image to the system clipboard.
    Here is our code. Do you have any idea? Thanks a lot for your help.
    // Create the image
    BufferedImage image = new BufferedImage(1024, 768, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g2 = image.createGraphics();
    drawSomething(g2);
    g2.dispose();
    // Put the image into the system clipboard
    ImageSelection handler = new ImageSelection(image);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(handler, handler);
    * An implementation of Transferable and ClipboardOwner to be used with
    * images.
    public class ImageSelection implements Transferable, ClipboardOwner {
        private static final DataFlavor flavors[] = {DataFlavor.imageFlavor};
        private Image image;
        public ImageSelection(Image imageToCopy) {
            this.image = imageToCopy;
        // Interface ClipboardOwner
        public void lostOwnership(Clipboard clipboard, Transferable transferable) {
            image = null;
        // Interface Transferable
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException,
                                                                IOException {
            if (isDataFlavorSupported(flavor)) {
                return image;
            else {
                throw new UnsupportedFlavorException(flavor);
        public DataFlavor[] getTransferDataFlavors() {
            return flavors;
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavor.equals(flavors[0]);
    }

    why dont u use other data structure to store the image , which will take less memory.

  • I had all photos on a Windows desktop.  Got a mac laptop, installed LR5, and put all images from Windows onto an external hard drive.  When I go to import them into LR on the Mac, they are all locked.  Help, please.  Thanks

    I had all photos on a Windows desktop.  Got a mac laptop, installed LR5, and put all images from Windows onto an external hard drive.  When I go to import them into LR on the mac, they are all locked.  Help, please!

    "I plugged the external into the Mac and moved a folder of images onto the desktop.  It looks like it went from read only to not locked.  Is this possible?"
    Yes, that's exactly what happened. If you buy another drive, you could copy from your existing drive to the new and your files will be read/write. The new drive will have to be formatted as an HFS drive (that's the Mac's format). If you need to format it, you use Disk Utility which is in the Utilities folder on your Mac. Be careful with that -- it wipes out whatever is currently on the drive. Make sure you format the right drive.
    I keep all my images on an external drive, too. In fact, I have two matching drives and sync them so I always have a backup.

Maybe you are looking for

  • Questions about PO creation / update / cancel interfaces

    Hi there, An E-Business Suite 11.5.10.2 customer wants to use the 11i PO creation / update / cancel interfaces in order to manage Purchase Orders created from a 3rd party system. I've been through the 'Oracle Purchasing Open Interfaces' guide (115mfg

  • Adobe creative suite 5.5 mc serial.

    I have legal adobe creative suite 5.5 for mac. When i install its asks serial, which is located on dvd cover, after enter it insalls product, after installing it asks serial again, after enter it says :serial number is not valid for this product. Rei

  • Problem in LDAP Configuration

    Hello everyone, I have a portal with java stack and i can create users from portal. But i am facing the problem while seeing the users in LDAP. For that i did the following... system admin->sys configuration->UM Configuration->LDAP server ->... here

  • GPS coordinates with minutes and seconds always 0

    I noticed the geotagged photos from my Android phone (Samsung Galaxy S3 with Android 4.3.1 Jelly Bean) have GPS coordinates always rounded to integers in Aperture. However when viewing the photo coordinates on the phone directly before importing in A

  • Database creation failed. review

    Hi! Thank Colin to help me. I have used the oracle enterprise edition. The log file shows: - ERROR: The 'CREATE DATABASE' statement for the sid1 database failed. egrep failed to find 'ORA-' error in the file: /u01/app/oracle/admin/sid1/create/crdbsid