Get Images from jar. getResource() not working

I've read some of the posts in the forum and I've tried the solutions but still cant get the images in my program.
I'll write all the things I've tried (All of them works fine when I run them from bluej):
1- The code used in the jar files in demo folder of jdk:
/** Inside the main class: */
private static ResourceBundle resources;  
    static {
        try {
            resources = ResourceBundle.getBundle("resources.Recursos", Locale.getDefault());
        } catch (MissingResourceException mre) {
            JOptionPane.showMessageDialog(new JFrame(), "ResourceBundle not found","Error",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
public String getResourceString(String nm)
        String str;
        try {       
            str = resources.getString(nm);   
              } catch (MissingResourceException mre) {       
            str = null;
        return str;
    public URL getResource(String key)
        String name = getResourceString(key);
        if (name != null)
            URL url = getClass().getResource(name); //  Here is the exception
            return url;  
        return null;
    public ImageIcon loadImage(String image_name)
        URL image_url = null;    
        try
            image_url = getResource(image_name);             
            if (image_url != null)
                return new ImageIcon(image_url);
            else
            return null;                  
        }catch(Exception e)
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage() + "In load Image","Error",JOptionPane.ERROR_MESSAGE);
            return null;
/** Inside the constructor */
abrirButton = new JButton(loadImage("open"));
}//End of the class}
The ResourceBundle is a file named: Recursos.properties and it's in a folder inside the folder of my *.class and *.java And have this information:
Title=Recursos
ElementTreeFrameTitle=Elements
ViewportBackingStore=false
open=resources/open24.gif
save=resources/saveAs24.gif
cut=resources/cut24.gif
copy=resources/copy24.gif
paste=resources/paste24.gif
analisis=resources/bean24.gif
This one, runs with the jar, but the images are not in the buttons and I get the Dialog message telling me that there was an error in loadImage. Check that method. I used this dialogs to track the error and the exception it's generated by:
URL url = getClass().getResource(name);
in public URL getResource(String key) method.
2- I also tried to follow the instructions of this article that describes how to get resources from jars:
http://www.javaworld.com/javaworld/jw-07-1998/jw-07-jar-p2.html
This is the first page of the article:
http://www.javaworld.com/javaworld/jw-07-1998/jw-07-jar.html
And I did something like this:
/** Inside constructor */
abrirButton = new JButton(new ImageIcon(getImageFromJAR("Imagenes/open24.gif")));
/** Inside of my main class */
public Image getImageFromJAR(String fileName)
           try{
           if( fileName == null ) return null;          
           Image image = null;
           Toolkit toolkit = Toolkit.getDefaultToolkit();          
            image = toolkit.getImage( getClass().getResource(fileName) );           
            return image;
            }catch(Exception exc){
                JOptionPane.showMessageDialog(new JFrame(), "Exception loading the image","Error",JOptionPane.ERROR_MESSAGE);
                return null;
...The images in this one are in the folder Imagenes inside the folder of my *.class and *.java
This one work fine in bluej too, but the jar... It doesn't even start.
3- And the last one.
abrirButton = new JButton(new ImageIcon(getClass().getResource("Imagenes/open24.gif"));Works fine in bluej, not running in jar.
Am I doing something wrong? Please somebody help me.
thanks in advance

Are you putting the image files inside the jar? If you are, then use "jar tf jarfile.jar" to display the contents of the jar and make sure the files are there and inside the right directory. If you are not, then you can not use getClass().getResource() from a jar file because it will look inside the jar file.
If you are getting an error message, please post it.

Similar Messages

  • Rich text box used in Infopath Form not displaying option to get images from Computer

    Hello,
    We have used "Rich text box" in Infopath Form which is not displaying option to get images from Computer.
    Options available are : From Address, From SharePoint
    But if we Rich text box in list, then it works fine with "From Computer" option.
    can you please help me out to get this option.
    Thanks in advance.
    REgards,
    Jayashri

    Hi,
    From your description, there is no “From Computer” option to get images with rich text box in InfoPath form.
    Per my knowledge, by design there are “From Address” and “From SharePoint” options without “From Computer” option in rich text box in InfoPath form. As a workaround, you can develop a custom InfoPath Rich Text box to do it.
    About developing a custom InfoPath control, I suggest you create a new thread on the forum “Visual Studio Tools for Office”, more experts will assist you with InfoPath development.
    Visual Studio Tools for Office:
    https://social.msdn.microsoft.com/Forums/office/en-US/home?forum=vsto&filter=alltypes&sort=lastpostdesc
    Thanks,
    Dean Wang

  • I am having trouble printing a PDF document. Whenever I click print nothing happens but when I am printing documents from Word, Excel etc they print without a problem. I've tried printing as image but that did not work. I uninstalled Adobe Reader XI and d

    I am having trouble printing a PDF document. Whenever I click print nothing happens but when I am printing documents from Word, Excel etc they print without a problem. I've tried printing as image but that did not work. I uninstalled Adobe Reader XI and downloaded Adobe Reader X instead and that still doesn't work. I have Windows 7.

    Hello,
    Please follow the link to troubleshoot the printing issues with Adobe Reader:- Troubleshoot PDF printing | Acrobat, Reader.
    Regards,
    Nakul

  • Get-MailboxSentItemsConfiguration Set-MailboxSentItemsConfiguration From Only (still) not working

    Hello,
    I would like to ask a question, hopeing it is resolved in some way and i missed it.
    I have installed SP3 Rollup 4 on our Exchange 2010 server.
    This added 2 new Powershell commands
    Get-MailboxSentItemsConfiguration
    Set-MailboxSentItemsConfiguration
    This can be used to manipulate where mail is stored in the send items.
    Sender - e-mails sent using SendAs or Send-on-Behalf-of permissions are saved only in the Sent Items folder of the Sender (UserA);
    SenderAndFrom – e-mails sent using SendAs or Send-on-Behalf-of permissions are saved in the Sent Items folder of the Sender and the mailbox on which the permissions are assigned (in our example, both UserA and UserB);
    From – e-mails sent using SendAs or Send-on-Behalf-of permissions are saved in the Sent Items folder of only the mailbox on which the permissions are assigned (in our example, UserB)
    What we really want it to use the From only way.
    We use a shared team mailbox and use that as primary, as a second mailbox users get a trusted non shared mailbox. Mail sent from the trusted mailbox should only be in the send items from the actual sender, not both.
    2 sites report that the From field is reserved for Future Use, or bugged and does not work is intened.
    Here is is stated on 1 July 2013
    http://technet.microsoft.com/en-us/library/jj884078(v=exchg.141).aspx
    From Reserved for future use. To save the messages sent as this mailbox in the Sent Items folder of this mailbox, use SenderAndFrom value.
    That was on 26 March 2013
    http://www.msexchange.org/kbase/ExchangeServerTips/ExchangeServer2010/OutlookOWA/sent-items-behavior-shared-mailboxes-update.html
    NOTE 1: the From value does not work as expected... It basically performs the same action as the SenderAndFromvalue, meaning it saves the e-mail in both mailboxes. This is still the case in Rollup 5 v2.
    We are on 3 March 2014 now, is this still bugged, did i miss something, or is there an ETA when this will be fixed ?
    Looking foward to any replies.
    Kind regards,
    Jeroen van Velzen

    I am using a shared mailbox (with a disabled account) where I get sent items and also deleted items placed in the right folders.
    I think it’s just a matter of how you configure Outlook. It works well for me in both Outlook 2010 and Outlook 2013, cached mode and also online mode. You can add a shared mailbox to your Outlook profile in at least two ways where one of them doesn’t work
    but the other does.
    If you add the shared mailbox via the File tab/Account settings/New/ and just enter the e-mail address of the shared mailbox in the Auto Account Setup page. No name, no password, just the e-mail address and click Next and voila “Your e-mail account is successfully
    configured”. After restarting Outlook you will find the shared mailbox below your own in the left pane.
    If you click the inbox ones in the shared mailbox and then open a new mail you will see the shared mailbox display name in the From field. After sending the mail you will see the mail in the Sent Items folder of the shared mailbox. If you delete a mail in
    the shared mailbox you will see it in Deleted items folder of the shared mailbox.
    The prerequisits for this is that you have “full access” and “send as” rights of the shared mailbox.
    This was accomplished without using the Set-MailboxSentItemsConfiguration command.
    We are running Exchange 2010 SP3 RU4.

  • Problem loading image from jar file referenced by jar file

    First, I searched this one and no, I didn't find an answer. Loading images from jar files has been pretty much done to death but my problem is different. Please read on.
    I have my application, a straight up executable running from Eclipse. It uses a jar file, call it JarA. JarA launches a GUI that is located in another jar file. Call it JarB. To recap:
    My application calls JarA -> JarA loads classes from JarB -> JarB looks for images to place in a GUI it wants to show on the screen
    When JarB goes to load an image the following happens:
    java.lang.NullPointerException
         at sun.misc.URLClassPath$3.run(URLClassPath.java:316)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:313)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:290)
         at sun.misc.URLClassPath.findResource(URLClassPath.java:141)
         at java.net.URLClassLoader$2.run(URLClassLoader.java:362)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findResource(URLClassLoader.java:359)
         at java.lang.ClassLoader.getResource(ClassLoader.java:977)
         at org.cubrc.gmshell.gui.MainWin.preInit(MainWin.java:152)
         at org.cubrc.gmshell.gui.MainWin.<init>(MainWin.java:135)
    The code from JarB that loads the image looks like this:
              URL[] oSearch = {Main.class.getResource("images/")};
              URLClassLoader oLoader = new URLClassLoader(oSearch);
              imgIcon = new ImageIcon(oLoader.getResource("icon.gif"));
              imgMatchRunning = new ImageIcon(oLoader.getResource("gears.gif"));
              imgMatchStill = new ImageIcon(oLoader.getResource("gears-still.gif"));
              imgMagnify = new ImageIcon(oLoader.getResource("magnify.gif"));This looks right to me and JarB certainly has an images directory with those files. But I'm in hell right now because I don't know where to place the images to make this work or if you can even attempt to load images with a dependency chain like this.
    Any help very appreciated!

    Have you tried to move your image-files out of the jar file and place them in the sam folder as the jar-file? I think that would help.
    When you try to load the image-file you get the NullPointerException because the program tries to read a file it can't find. Remember that a jar file IS a file and not a directory.
    If you want to read somthing inside the jar-file you need to encode it first.
    Have you tried to read the jar-file with winRar. It makes it easy to add and remove files in your jar-file.

  • Reading Images from JAR Files

    Hi,
    I am having a very difficult time being able to read images from a JAR file via my Applet. I have tried everything that I know about with no luck. The only way I can get this to work is to store the images individually in a sub directory of public_html on the websever. This works, but I would like the images to come down in a JAR file for performance reasons.
    I am using Internet Explorer 5.5 for my browser. I checked the options and everything seems to be in order, but......
    I would appreciate any feedback that anyone might have on this topic..........
    Thank You....

    once in a jar file i inserted a image
    the jar file on clicking starts an frame.
    so the image was for getting that image at the icon place at top and at minimized window
    i could not get that image from jar file by new imageicon().getimage();
    but i get the image if it is in the directory in which jar file is.....
    can one explain the reason

  • Loading image from jars only once in oracle forms 10g

    Hi,
    I have an oracle forms 10g application which loads image from a jar. Every time i click on a button "A" that loads the image "image" on another button "B" in the same screen, a message is displayed in the java console "Loaded image: jar:https://+IP+/forms/java/+myjar+.jar!/image.gif". So after 10 clicks, i get the same message displayed 10 times. In the form, i've called:
    SET_CUSTOM_PROPERTY(p_object_name, 1, 'IMAGE_NAME_ON', '/'||p_image_name);My question is the following:
    - is there a way to load this image once and use it later without having to load it every time i clik on "A"? if yes, how?
    P.S.: if this thread shouldn't be posted in this forum, please redirect me to the right one.
    Thanks in advance

    Ah okay.
    I'm using the rolloverbutton.jar (RollOver Button PJC) [RolloverButton.java -> authors: Steve Button, Duncan Mills].
    Here is the part concerning the IMAGE_NAME_ON function:
    // make sure we are in rollover mode
    enableRollover();
    log("setProperty - IMAGE_NAME_ON value=" + value.toString());
    // load the requested image
    m_imageNameOn = (String) value;
    loadImage(ON,m_imageNameOn);
    // reset the currrently drawn image if needed
    setImage(ON,m_state);
    return true;where loadImage function is:
        URL imageURL = null;
        boolean loadSuccess = false;
        //JAR
        log("Searching JAR for " + imageName);
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          log("URL: " + imageURL.toString());
          try
            m_images[which] = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            log("Image found: " + imageURL.toString());
          catch (Exception ilex)
            log("Error loading image from JAR: " + ilex.toString());
        else
          log("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          log("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
              log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          log("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
                    log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          log("Error image " + imageName + " could not be located");In this case, what shall i modify?
    Thanks in advance

  • Error while getting  image from database in SUP using ios?

    Hi All,
      Im developing native iOS application using sup 2.1.3 . Im getting error While retrieving  image from SUP database. Here i'm trying to get image from database and show in imageView.can any one help me how to fix this issue?
    In database image datatype is  'LONG Binary' .
    My table Schema:
    CREATE TABLE dba.ImagesTable (
    RowID INT NOT NULL,
    ImageName VARCHAR(20) NOT NULL,
    PhotoData LONG BINARY NOT NULL,
    IN SYSTEM
    ALTER TABLE dba.ImagesTable
      ADD CONSTRAINT ASA137 PRIMARY KEY CLUSTERED (RowID)
    ALTER TABLE dba.ImagesTable
      ADD CONSTRAINT ASA138 UNIQUE NONCLUSTERED (RowID)
    in Xcode:
                [SUP107SUP107DB synchronize];
                SUP107ImagesTable *imgTable =[[SUP107ImagesTable alloc]init];
                SUP107ImagesTableList *list =[SUP107ImagesTable findAll];
                SUP107ImagesTable * oneRecord =[list objectAtIndex:0];
                NSLog(@"rowId:%d---imageName:%@---photoData:%@---photoLenght:%d",oneRecord.rowID,oneRecord.imageName,oneRecord.photoData,oneRecord.photoDataLength);
                NSData *tempData =[[NSData alloc]init];
                SUPBigBinary *responseBinaryData = (SUPBigBinary *)oneRecord.photoData.value;
                @try {
                    [responseBinaryData openForWrite:[oneRecord.photoData length]];
                    [responseBinaryData write:tempData];
                @catch (NSException *exception) {
                    NSLog(@"exception: %@",[exception description]);
                UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,100,100)];
                [self.window addSubview:imgView];
                UIImage * tempImage =[UIImage imageWithData:tempData];
                imgView.image = tempImage;
                [responseBinaryData close];
    Error Log:
    2014-04-02 18:42:15.150 SUP102[2873:70b] rowId:1---imageName:Apple---photoData:SUPBigBinary: column=c pending=1 allow_pending_state=1 table=sup107_1_0_imagestable mbo=0x0 key=(null) ---photoLenght:90656
    Printing description of responseBinaryData:
    <OS_dispatch_data: data[0xc891b40] = { leaf, size = 90656, buf = 0x1213a000 }>
    2014-04-02 18:42:33.304 SUP102[2873:70b] -[OS_dispatch_data openForWrite:]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.305 SUP102[2873:70b] exception: -[OS_dispatch_data openForWrite:]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.305 SUP102[2873:70b] -[OS_dispatch_data close]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.306 SUP102[2873:70b] [ERROR] [AppDelegate.m:497] NSInvalidArgumentException: -[OS_dispatch_data close]: unrecognized selector sent to instance 0xc891b40

    This thread talks about uploading image to SAP from a IOS device,Sending Image to SAP via iOS Native app (SUP 2.1.3)
    Midhun VP

  • Consuming PI Webservice from Webdynpro Java Not working

    Hello SAP,
    Environment: CE 7.2.
    Resolution expected immediately, Helpful answer is highly appreciated.
    Is the namespace should not exceed 60char for PI Webservice, for executing the webservice from Webdynpro Java.
    I tried with all the options in executing the PI Service from Webdynpro Java, None of the options worked. I am facing the below error while I was calling the PI Webservice.
    I don't see any problem from Webdynpro Java, what ever the procedure I have followed is the standard procedure.
    Fortunately when I execute the service from Webservice Navigator, it is working as expected. The same webservice when I consume it from Webdynpro Java it is not working
    Options tried so far:
    1) Published the Services to Service Registry and there by consuming the PI Service from Service Registry - Not worked
    2) Tweaked the URL with few options - Not worked (Tweaking the URL, ex: portType, Binding)
    3) Changing the Business Systems in PI and there after calling the service - Not worked
    4) Initializing the code, instead of creating Service Controller and calling the PI Service - Not worked.
    5) Created a Provider System and tried to call the PI Webservice from Provider System - Not Worked
    For all the Options, I am facing the same error which is provided in the screenshot.
    Below procedure which I have followed for calling the PI Webservice:
    1) Created Adaptive Webservice Model
    2) Provided PI Webservice URL (It prompts for PI System UserId and Password)
    3) Selected Option - No Service Group Configuration
    4) Provided Logical Destination
    6) Completed creation of Model
    7) Added the model as a UsedModel
    8) Right Click on Comp Contr. and selected Apply Template and Created a ServiceController for the model (Entire mapping to comp contr, Initializing the nodes is taken care by Service Contr.)
    9) Created an Template Action button and there by calling execute method which is auto rendered from CompContr..
    10) Build the project.
    11) Activated the code and Run the Application.
    12) Getting the below error which is showed in the message.
    ERROR MESSAGE:
    Exception on execution of web service on destination 'GetPIHRPeopleData' for operation 'SI_CreateHRPeopleData_OS' in interface 'SI_CreatePeopleCompany_OS'

    Hi Sankar,
    If the webservice is working fine in the Wsnavigator then there is some problem with importing the webservice in webdynpro for Java. Please check the required parameter for creating the Adaptive Webservice Model. After adding in the used model and compoent controller binding, you need to write code for to execute the webservice model.
    Please check the code for initialization and execution for the webservice and then test it.
    Best Regards,
    Arun Jaiswal

  • TS1362 I downloaded two cd's last night and I am un able to play some songs cause it tells me I am this computer is unauthorized to play some songs,I did what it said about going to store to get authorized and still will not work,not happy at all!

    I downloaded two cd's last night and I am un able to play some songs cause it tells me I am this computer is unauthorized to play some songs,I did what it said about going to store to get authorized and still will not work,not happy at all!  I NEED HELP OR MY MONEY BACK NOW!

    There seems to be an occasional issue with downloads from the store. They prompt for authorization when they are in fact corrupt/incomplete in some fashion. Try deleting the problem tracks (do not hide from iTunes in the cloud), close iTunes and reopen, go to iTunes Store > Qucklinks > Purchased > Music > Not on this computer. Select a few tracks to download then click the icon that appears at the top-right of the iTunes window.. Untick the box that reads Allow simultaneous downloads. Proceed with the rest of your eligible purchases.
    If you still have a problem use the Report a problem links in your account history to contact the iTunes Store support team.
    tt2

  • Where does the data get saved from (notepad) or Notes on Windows Mobile 5?

    Where does the data get saved from (notepad) or Notes on Windows Mobile 5?
    (ON the Phone)  Sticky note like program WM5
    I ask because I synced my Blackjack 1 to my pc after about a year and MANY notes later, All the notes from the PC remained but ALL new notes on phone (a years worth) were deleted from the phone.
    I would like to attempt a data recovery on my mobile device- that was an insane endeavor but i got it to work now i just need to know what to look for (what type of files to recover) and or where to recover from?
    I did make the phone a drive already and have data recovery software that can pull deleted files from the phone in fat or raw data format.
    Thanks.

    Hi,
    I think this is not the best forum for your question. This forum is for Microsoft Exchange Server's mobile connectivity issues.
    Regards,
    Zoltán
    http://www.clamagent.org - Free Antivirus for Exchange
    http://www.it-pro.hu
    http://emaildetektiv.hu

  • Select * from tab is not working in oracle 10g

    select * from tab is not working in oracle 10g. But at the same time,
    select * from <<table>> is working.
    Please advise me.

    This works for me in 10.2.0.2
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.2.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL> select * from tab;
    TNAME                          TABTYPE            CLUSTERID
    LOAN_DETAIL                    TABLE
    PLAN_TABLE                     TABLE
    ...

  • I am using Windows 7 64-bit. After installing Photoshop Elements 13 and trying to run it I always get the message: Photoshop does not work anymore. And it doesn't.

    I am using Windows 7 64-bit. After installing Photoshop Elements 13 and trying to run it I always get the message: Photoshop does not work anymore. And it doesn't.

    Hi Hardy Tasso,
    Are you seeing this problem since first launch of PSE13 after installation or recently?
    Please try:
    Keep Ctrl + Alt + Shift keys pressed while launching PSE13 Editor and click OK on the dialog that comes next.
    Thanks,
    Anwesha

  • When I unplug Apple headphones from my MacBook Pro sond from internal speakers not work, and system soud preferences displayed: Output: optical digital out port only

    When I unplug Apple headphones from my MacBook Pro sond from internal speakers not work, and system soud preferences displayed: Output: optical digital out port only

    If you see a red light in the audio output port, then the internal switch is stuck.  Insert the earphone plug a few times and see if you can trip the switch.  If that fails, insert a cocktail stirrer and the like and jiggle it around inside.  If that fails, take it to an Apple store and have the technicians at the genius bar do it for you.
    Ciao.

  • How do I get images from Aperture into print shop for mac?

    Friends,
    I have Print Shop for Mac and Aperture. How do I get images from Aperture into Print Shop? I'musing managed images with previews. Is there any option besides exporting to the desktop and importing?
    Thanks!
    Steve

    if you have previews turned on in Aperture and they're all genereated, you can simply drag-n-drop them into any application (just about). drag-n-drop is essentially the same as copy/paste as long as the application is setup to accept "drops" onto its windows.
    otherwise, if you're running Leopard (10.5) as your version of Mac OS X, when you import (or whatever it is in PrintShop), you should get a file selection dialog. from here, scroll down the left-hand side bar set of icons. near the bottom is a group called "Media". click on the triangle to open the group, choose Photos, and from here you should see an Aperture icon. click this and you'll see your whole library (or at least the portion of it that you have previews generated for. select the photo you want and viola!
    scott

Maybe you are looking for