Displaying a image in a gui

i was wondering how i can display an image using jframe
what steps would i need to take to get it working

Yes, there are several ways you can get an image icon either from local disk or network. I have used the simplest approach and shown here how to display an image in user interface.
As suggested by DrLaszloJamf, using URL is good approach. Locate your image, construct the URL and then create the image icon using that URL.
Sample code for creating image icon:
     * Locates the image icon at specified {@code path} using given class reference
     * and a short description of the image.
     * Once the URL is resolved it creates an image icon and returns the same.
     * @param cl The class which is used as reference to locate the image icon.
     * @param path The pathname for the image.
     * @param description A brief textual description of the image.
     * @return An image icon. It returns {@code null} if given path can not be resolved
     *               or failed to load the image icon.
    public static ImageIcon createImageIcon(Class cl, String path,
            String description) {
        // Validate inputs here.
        try {
            URL imgURL = cl.getResource(path);
            if (description != null) {
                return new ImageIcon(imgURL, description);
            } else {
                return new ImageIcon(imgURL);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
    }Thanks,
Mrityunjoy
Edited by: mrityunjoy on 6 Feb, 2009 10:22 AM

Similar Messages

  • Displaying jpg images in same GUI as buttons

    Hi,
    I am writing an application that requiers the user to enter the location of a jpg file and this image is then displayed on screen along with a number of buttons.
    I am having trouble because I cannot get the image - which I have used mediatracker for, into a JPanel.
    I need to use the MediaTracker for other operations that I am pewrforming upon the image
    Any suggestions?
    Jane

    I am writing an application that requiers the user to
    enter the location of a jpg file and this image is
    then displayed on screen along with a number of
    buttons.
    I am having trouble because I cannot get the image -
    which I have used mediatracker for, into a JPanel.
    I need to use the MediaTracker for other operations
    that I am pewrforming upon the imageSee JLabel and ImageIcon
    JPanel panel = new JPanel();
    JLabel label = new JLabel();
    panel.add(label);
    label.setIcon(icon);

  • How do i display an image on a GUI?

    I am making a GUI, and I was trying to post an image(s) on it. I tried various things including turning it into an applet and using the paint(Graphics g) method, but it didn't show up.
    Thanks!

    calm down chief, these people work for a living. They will get to you. Here is a GUI that I did a while ago that has images in it. Maybe it will help you. Let me know.
    import java.awt.*;
    import javax.swing.*;
    public class NestedPanels {
        public static void main(String[] args){
            ImageIcon pic1 = new ImageIcon("nasa1.jpg");
            ImageIcon pic2 = new ImageIcon("nasa2.jpg");
            ImageIcon pic3 = new ImageIcon("nasa3.jpg");
            ImageIcon pic4 = new ImageIcon("whale.jpg");
            JFrame frame = new JFrame("Nested Panels");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //first subpanel
            JPanel subPanel1= new JPanel();
            subPanel1.setPreferredSize(new Dimension(600,600));
            subPanel1.setBackground(Color.white);
            JLabel label1 = new JLabel ("pic one",pic1,0);
            JLabel label2 = new JLabel("pic two",pic2,0);
            subPanel1.add(label1);
            subPanel1.add(label2);
            //second subpanel
            JPanel subPanel2 = new JPanel();
            subPanel2.setPreferredSize(new Dimension(600,600));
            subPanel2.setBackground(Color.white);
            JLabel label3 = new JLabel("pic three",pic3,0);
            JLabel label4 = new JLabel("pic four",pic4,0);
            subPanel2.add (label3);
            subPanel2.add(label4);
            //primary panel
            JPanel primary = new JPanel();
            primary.setBackground(Color.white);
            primary.add(subPanel1);
            primary.add(subPanel2);
            frame.getContentPane().add(primary);
            frame.pack();
            frame.setVisible(true);          
    }You gotta make sure that the pics are in the same folder ok bud?

  • Displaying an image in a GUI

    Hi,
    Been looking into diplaying an image in a windows app for 2 days and i really can't believe how much trouble i'm having getting anything to work.
    All the tutorials i'm finding either don't work orthey are only for applets, can anyone help me out getting started with either a good tutorial or some example code they know to work? I am also getting the null pointer exception problem mentioned by another poster, tried putting the image files everywhere they might be looked for.
    I'm getting quite desperate here
    Thanks.

    have an image file test.gif ij the same folder as your .java file
    this will show a JLabel with an icon, in the middle of a panel, with the same
    image set as the bacground of the panel
    import javax.swing.*;
    import java.awt.*;
    class Testing extends JFrame
      Image img;
      public Testing()
        setSize(600,400);
        setLocation(300,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        BackgroundPanel bp = new BackgroundPanel();
        bp.setLayout(new GridBagLayout());
        if(img != null) bp.add(new JLabel(new ImageIcon(img)),new GridBagConstraints());
        getContentPane().add(bp);
      class BackgroundPanel extends JPanel
        public BackgroundPanel()
          try
            img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));
          catch(Exception e){}
        public void paintComponent(Graphics g)
          super.paintComponent(g);
          if(img != null) g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
      public static void main(String[] args) {new Testing().setVisible(true);}
    }

  • Displaying Images in my GUI

    I have created a GUI that lets me display images that a user selects from a file. However is it possible to display an image that has not yet been written to a file?
    I have a class that takes an image object, perfoms operations on it then maps this to a new image object. Would it be possible to display this image before it has actually been written to file? If anyone out there has ideas i'll be very grateful.
    Here is an example of how I map one image to another:
         // Creates an image object.
         MyImage imageRight = new MyImage();
         // Now read in the image file
    // Create new object for reading image
         MyImage imageCenter = new MyImage(imageRight.getWidth(), imageRight.getHeight());
    /* Copy the pixel information from image that was read in to the
         new image */
         for (int y = 0; y < imageRight.getWidth(); y++) {
                   for (int x = 0; x < imageRight.getHeight(); x++) {
              /* Get the values from imageOne */
              int red = imageRight.getRed(x,y);
              int green = imageRight.getGreen(x,y);
              int blue = imageRight.getBlue(x,y);
              /* Put these values into imageTwo */
              imageCenter.setRGB(x, y, red, green, blue);
    At this point before I write the file, you can see that imageCenter holds all the attributes of an image. Now can I display this image object in my GUI?
    I hope someone can help me as this is really important.
    Thanks again.

    Look into the graphics's drawimage method.
    ;o)
    V.V.

  • Make a GUI display an image

    Im having trouble adding an image to a GUI, ive tryed adding it the same way I would add a JLabel (seeing as there both swing components, i asumed it would work) but it wont work, heres my code.
    import javax.swing.*;
    import java.awt.*;
    public class HelloWorldSwing
        private static void createAndShowGUI()
            JFrame frame = new JFrame("My Gui");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(200, 50);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            ImageIcon image = new ImageIcon("Logo", "C:/Windows/System32/oobe/images/mslogo.jpg" );
            frame.getContentPane().add(image);
            frame.validate();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }What am I doing wrong ?

    Im having trouble adding an image to a GUI, ive tryed
    adding it the same way I would add a JLabel (seeing
    as there both swing components...An ImageIcon does not inherit from Component. You cannot add an ImageIcon with add()...

  • Noob GUI question - Display an Image from a file

    I've done a bit of Java before but never a user interface. To start I'm just trying to display an image in a Panel, and can't even get that far!
    Here is my code (all the relevant bits of it...), would be much appreciated if someone could explain why it doesn't work. (Just so you know, breakpoints have shown that the code IS getting to the end of the 'try' block successfully)
    public class PictureBox extends Canvas {
        private Image m_image;
        public PictureBox()
            m_image = null;
        public PictureBox(Image image)
            m_image = image;
        public void setImage(Image image)
            m_image = image;
        @Override public void paint(Graphics g)
            if(m_image != null)
                g.drawImage(m_image, 0, 0, this);
        private void initialise()
            m_pb = new PictureBox();
            jPanel1.add(m_pb);
            jPanel1.add(new JButton());
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            try
                jFileChooser1.showOpenDialog(jPanel1);
                File f = jFileChooser1.getSelectedFile();
                m_image = ImageIO.read(f);
                m_pb.setImage(m_image);
                m_pb.repaint();
            catch(Exception e)
                return;
        }

    I don't know which resource you are using as a guide, but throw it away immediately. You are using AWT here, I would highly recommend you switch to Swing. It has a very nice tutorial that will get you up and running in no time:
    http://java.sun.com/docs/books/tutorial/uiswing/

  • Displaying 3D image on DMS

    Dear all,
    Can any tell me what is the necessary steps for displaying 3D file in DMS like STL file.
    I have done in Workstation Application
    suffix- stl
    File format- *.stl
    but not displaying the image even i have installed GUI with ECL Viewer.
    Thanks & Regards.
    Rajesh Choudhary.

    Hello,
    in spro defining workstation applications mark the entry for STL and doubleclick on "Define workstation application in network". At least for the application type 1 (display) enter
    "EAIWeb.webviewer3D.1 %SAP-CONTROL%" in the field "Application (path and program name)"
    regards Iring

  • HELP! how to display an image when clicking on JLabel?

    hi. new to the forums. anyway, i need help in displaying an image.
    what i'm trying to do is when clicking on a JLabel using mouseClicked, an image will show and when the image is clicked it will disappear. i've searched and searched and have not found anything useful. thanks...

    thanks.
    searched on the setIcon, didn't find anything. btw, i know how to set the icon on the JLabel. i'm trying to figure out how i can get it that when i click on the JLabel by using the mouseClicked (or maybe even mousePressed) listener, the image pops up and when i click on the image, it closes or disappears.
    btw, i'm using the netBeans GUI builder for this. thanks again.

  • Aperture 3 project does not display any images in one Project

    This is a strange situation.  The bullets below outline the situation:
    The project does not display any images
    When I place the pointer over the project it shows there are 500+ images
    I have located the RAW images stored in my aperture library
    I can pull up the images using a smart folder and searching for photos taken on the event day
    This is happening only to one of my projects that I know of (weird!!)
    I have tried to 're-add' the image by both importing and dragging and dropping into the project, neither works
    I tried the following basics:
    Fixed permissions
    Rebuilt the database
    Tried to re-import the data, but when I have the 'don't import duplicates' these are not an option
    Found the images in my Aperture library
    I created another project and drug all of the images into that project
    Any idea how I can fix this?
    My fear is that if I delete the original project, the original master images will be deleted.

    The most common cause of this is some sort of stuff in the search box at the top of the browser that you don't expect to be there. Just clear it and all your images should show up.
    RB
    One note - if you drug your images from one project to another it moves them vs copies them unless you hold down the option key.

  • Problem with displaying BLOB images on JSP page using a servlet

    hi. I have a big problem with displaying BLOB images using JSP. I have a servlet that connects to the oracle database, gets a BLOB image , reads it, and then displays it using a BinaryStream. The problem is , this works only when i directly call that servlet, that is http://localhost:8080/ImageServlet. It doesn't work when i try to use that servlet to display my image on my JSP page (my JSP page displays only a broken-image icon ) I tried several coding approaches with my servlet (used both Blob and BLOB objects), and they work just fine as long as i display images explicitly using only the servlet.
    Here's what i use : ORACLE 10g XE , Eclipse 3.1.2, Tomcat 5.5.16 , JDK 1.5
    here is one of my image servlet's working versions (the essential part of it) :
                   BLOB blob=null;
              rset=st.executeQuery("SELECT * FROM IMAGES WHERE ID=1");
              while (rset.next())
                   blob=((OracleResultSet)rset).getBLOB(2);
              response.reset();
              response.setContentType("image/jpeg");
              response.addHeader("Content-Disposition","filename=42.jpeg");
                    ServletOutputStream ostr=response.getOutputStream();
                   InputStream istr=blob.getBinaryStream(1L);
                    int size=blob.getBufferSize();
              int len=-1;
                    byte[] buff = new byte[size];
                         while ((len=istr.read( buff ))!=-1 ) {
                   ostr.write(buff,0,len);
             response.flushBuffer();
             ostr.close(); and my JSP page code :
    <img src="/ImageServlet" border="0"  > If you could just tell me what i'm doing wrong here , or if you could show me your own solutions to that problem , i would be very greatful ,cos i'm realy stuck here , and i'm rather pressed for time too. Hope someone can help.

    I turns out that it wasn't that big of a problem after all. All i had to do was to take the above code and place it into another JSP page instead of into a servlet like i did before. Then i just used that page as a source for my IMG tag in my first JSP. It works perfectly well. Why this doesn't work for servlets i still don't know, but it's not a problem form me anymore . Ofcourse if someone knows the answer , go ahead and write. I would still appriceatte it.
    here's the magic tag : <img src="ImageJSP.jsp" border="0"  > enjoy : )

  • Problem with display an image on JFrame in Java 6

    I'm trying to display an image on JFrame in this way:
    1.) I'm creating a variable in the class:
        private Image imgSpeaker = null;2.) I'm overiting the paint method:
    public void paint(Graphics g) {
            super.paint(g);   
            g.drawImage(imgSpeaker, 330, 230, null);  
        }3.) In the constructor I'm using this code:
       imgSpeaker = Toolkit.getDefaultToolkit().getImage("D:\\speaker.gif");
            MediaTracker trop = new MediaTracker(this);
            trop.addImage(imgSpeaker,0);
            try {
                trop.waitForID(0);    // waiting untill downloading progress will be complite
            } catch (Exception e) {
                System.err.println(e);
            }        The Image will be displayed on form, but if I catch the window and move it (for example: down as possible)
    the image is not refreshed (repainted). What I'm doing wrong? I've been used this solution in Java 5 and everything
    works perfectly. Any of described methods aren't depricated... Anyone can help me?

    Thanks for your code, I've been tryed to apply your solution (with create a Buffered Image), but it still not working correctly. Firstly, the image isn't loading, and secondly the basic problem is not give in. Why have you been using "bg2d.draw(img, x, y, w, h, frame);" not in the paint method?
    I'm use "Free Design" layout. Below I put on completly code from Netbeans.
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.image.BufferedImage;
    public class ImageTest extends javax.swing.JFrame {
        private Image imgSpeaker = null;
        private BufferedImage bi = null;
        private MediaTracker trop = null;
        public ImageTest() { 
                initComponents();
                trop = new java.awt.MediaTracker(this);
                imgSpeaker = java.awt.Toolkit.getDefaultToolkit().getImage("D:\\speaker.gif");
                try {
                    trop.addImage(imgSpeaker, 0);
                    trop.waitForID(0);
                } catch (java.lang.Exception e) {
                    java.lang.System.err.println(e);
                bi = new java.awt.image.BufferedImage(100, 100, java.awt.image.BufferedImage.TYPE_INT_RGB);
                java.awt.Graphics2D bg2d = (java.awt.Graphics2D) bi.createGraphics();
                trop.addImage(bi, 1);
    //            java.io.File f = new java.io.File("D:\\speaker.gif");
    //            try {
    //                bi = javax.imageio.ImageIO.read(f);
    //            } catch (IOException e) {
    //               java.lang.System.err.println(e);
        public void paint(Graphics g) {
    //      super.paint(g);
           try {                                                   
                trop.waitForAll();                                 
            } catch (Exception e) {
                System.err.println(e);
            g.drawImage(bi, 50, 100, imgSpeaker.getHeight(this), imgSpeaker.getHeight(this), this);
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("jButton1");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(283, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(44, 44, 44))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(252, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(25, 25, 25))
            pack();
        }// </editor-fold>
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ImageTest().setVisible(true);
        private javax.swing.JButton jButton1;
    }

  • Display BLOB (image) column in (interactive) report

    Hi,
    I have a field called "picture" in my table "details" which is of type BLOB. i also have a field for "MIMETYPE" and "filename"
    i additionally have a "name" and "description" columns which i need to display along with the picture as columns in a report (preferably interactive).
    i have also modified the BLOB display format as per
    http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/apex/r31/apex31nf/apex31blob.htm
    what i am missing is the correct query. if possible, i would like to control the size of the picture rendered within the report like say 40*50.
    I have also referred to the thread
    APEX 3.1 Display BLOB Image
    But i don't know how to place the
    dbms_lob.getlength("BLOB_CONTENT") as "BLOB_CONTENT"
    in my query.
    The above also makes the report column as of type "number". is this expected?
    Any help would be much appreciated.
    Regards,
    Ramakrishnan

    You haven't actually said what the problem is?
    >
    I have a field called "picture" in my table "details" which is of type BLOB. i also have a field for "MIMETYPE" and "filename"
    i additionally have a "name" and "description" columns which i need to display along with the picture as columns in a report (preferably interactive).
    i have also modified the BLOB display format as per
    http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/apex/r31/apex31nf/apex31blob.htm
    what i am missing is the correct query.
    I have also referred to the thread
    APEX 3.1 Display BLOB Image
    But i don't know how to place the
    dbms_lob.getlength("BLOB_CONTENT") as "BLOB_CONTENT"
    >
    Something like:
    select
              name
            , description
            , dbms_lob.getlength(picture) picture
    from
              details
    if possible, i would like to control the size of the picture rendered within the report like say 40*50.For images close to this size it's easy to do this for declarative BLOB images in interactive reports using CSS. Add a style sheet with:
    .apexir_WORKSHEET_DATA td[headers="PICTURE"] img {
      display: block;
      width: 40px;
      border: 1px solid #999;
      padding: 4px;
      background: #f6f6f6;
    }where the <tt>PICTURE</tt> value in the attribute selector is the table header ID of the image column. Setting only one dimension (in this case the width) scales the image with the correct aspect ratio. (The border, padding and background properties are just eye candy...)
    However, scaling large images in the browser this way is a huge waste of bandwidth and produces poorer quality images than creating proper scaled down versions using image tools. For improved performance and image quality, and where you require image-specific scaling you can use the database ORDImage object to produce thumbnail and preview versions automatically, as described in this blog post.

  • How to load an image without a gui? big problems...

    Hey guys, I usually try my best to not ask for help and figure stuff out myself. But this last week i've been having big problems with this work project.
    My goal is to load images from disk, and append them to each other to create one big image.
    The images are 0-9.jpg each file containing a number in it. then i create one big file with 4 numbers in it. called final.jpg.
    so far i can do all this, but whenever the program is finished, the application just keeps running. the program has literally gone through all the steps... i have a system.out.println printed on the last line after the main, after the class instantiation... and still it stays running.
    how do you guys load images without a gui? This program will probably be running under unix, so i can't create a (for component example)
    Panel() and media track the file load... so i'm pretty much stumped
    any help you guys can provide would be really incredibly helpfull at this point. I have searched these threads for a few hours without luck. I found only 1 real post related to my problem, but eventually they said use MediaTracker = new Mediatracker( new Panel() ); which i can't use. :(
    Thanks a lot guys.
    :D

    yeah tried doing that, didn't work either.
    UPDATE
    I FINALLY found a way...
    and here it is for others to find!
    public BufferedImage getImage(String filename) throws Exception {
    FileInputStream input = new FileInputStream( filename );
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( input );
    BufferedImage image = decoder.decodeAsBufferedImage();
    return image;
    it returns an image buffer, but it's better than nothing! :)
    atleast this functions under unix.

  • How do I display blob (image) in a Portal Report

    I am using 9ias 10222 and portal 30983 and I have a table that stores an image as a blob and have a varchar field to store the mime type. I have created a form to upload the image and can then query the form to display the image.
    How do I dislay the image in a Portal Report/Dynamic Page Component. I have followed note 68016.1 but the retrieve_img_data procedure does not work it gives a wwv-11230 error.
    Any ideas? Any help would be appreciated.
    Thanks
    Belinda

    Hi,
    Can you display what code you used for this? I followed note 172045.1 and everything compiles properly but when I run the report, I just get a box with a red X in it, like it is not finding the picture. I ran the procedure that downloads the image and it works fine from there. Thanks.

Maybe you are looking for

  • Send email from OWB with authenticated SMTP server (AUTH_LOGIN)

    Hi all, I want to send email from Oracle Warehouse Builder 11.2.0.2 using a SMTP server with basic authentication (AUTH_LOGIN). I've created an ACL for OWBSYS user according to note ID 1229769.1 in support.oracle.com. But, I need to configure again t

  • HT1688 Private Browsing? What does this do and should I have it turned ON or OFF?

    I updated phone and was wondering if I should have Private Browsing turned ON or OFF (under Safari menu) ??? I figured it was best to have ON figuring it would be blocking others (companies, etc) from getting any sort of info or access to anything? I

  • Indesign cs6 trial start problem

    I downloaded all files for the trial cs6, but could not see how to get the program running. I found the indesignservercs6.exe in my program files/adobe but clicking it does nothing. How do I get this running?

  • Hyperlink in Smartforms not vworking in Lotus Notes

    Hi, I want to add a hyperlink (e-mail address), in smartforms that get triggerred through Action Profiles. I am facing a problem where in the smartform is opened in Lotus Notes. While opening the e-mail in Lotus Notes and placing the cursor on the e-

  • Standard Extractor for Tax Details

    Hi all, Is there any standard extractor available to extract the Tax related data from the Accounting document. regards Vishu