javajframegetresource

getResource not retrieving images in Source Package


I am trying out a java with Ant slideshow in a video I found. I have made the output, and the window is appearing, but none of the images are being shown.

I suspect I have done something wrong pertaining to the getResource code i implentented. I expected that the getResource("/newsimages") would work and display all the images, but it won't.

package pbt2mainpage;
import java.awt.Image;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

public final class MainPage extends javax.swing.JFrame {

    public MainPage() {
        initComponents();
        show(position);
    }
    
    int position = 0;
public String[] takeimage()
{
    File f = new File(getClass().getResource("/newsimages").getFile());
    String[] Images = f.list();
    return Images;
}

public void show(int index)
{
    String[] Images = takeimage();
    String img = Images[index];
    ImageIcon icon = new ImageIcon(getClass().getResource("/newsimages/")+img);
    Image image = icon.getImage().getScaledInstance(news.getHeight(), news.getWidth(), Image.SCALE_SMOOTH);
    news.setIcon(new ImageIcon(image));
    
}
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        news = new javax.swing.JLabel();
        next = new javax.swing.JLabel();
        previous = new javax.swing.JLabel();
        background = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(news, new org.netbeans.lib.awtextra.AbsoluteConstraints(45, 55, 990, 360));

        next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbt2mainpage/next.png"))); // NOI18N
        next.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                nextMousePressed(evt);
            }
        });
        getContentPane().add(next, new org.netbeans.lib.awtextra.AbsoluteConstraints(1040, 200, -1, -1));

        previous.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbt2mainpage/previous.png"))); // NOI18N
        previous.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                previousMousePressed(evt);
            }
        });
        getContentPane().add(previous, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 200, -1, -1));

        background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbt2mainpage/For CPG.jpg"))); // NOI18N
        getContentPane().add(background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1080, 450));

        pack();
    }// </editor-fold>                        

    private void nextMousePressed(java.awt.event.MouseEvent evt) {                                  
        new Thread();
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        int p = this.news.getX();
        
        if(p>-1)
        {
          Animacion.Animacion.mover_izquierda(900, 200, 1, 2, news);
        }
        position=position+1;
        if(position>=takeimage().length)
        {
            position=takeimage().length-1;
        }
        show(position);
    }                                 

    private void previousMousePressed(java.awt.event.MouseEvent evt) {                                      
       new Thread();
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        int p=this.news.getX();
        
        if(p>-1)
        {
          Animacion.Animacion.mover_izquierda(900, 200, 1, 2, news);
        }
          position=position-1;
        if(position<0)
        {
            position=0;
        }
        show(position);
    }                                     

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            new MainPage().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel background;
    private javax.swing.JLabel news;
    private javax.swing.JLabel next;
    private javax.swing.JLabel previous;
    // End of variables declaration                   

Solution

  • File means File. This:

    new File(getClass().getResource("/newsimages").getFile());
    

    Does not work and cannot be made to work. Because those entries in your jar file are not files. They are jar entries.

    This is how you do it, from your own code later in your source:

    new ImageIcon(getClass().getResource("/newsimages/")+img);
    

    Though, you should be using MainPage.class.getResource instead (better style; does not break if you subclass, though that doesn't seem too relevant here).

    Your code makes a file object in order to list its contents. This is not an operation you can do. The classloading system simply does not have a 'list' primitive.

    Therefore, instead, you have a few choices:

    1. Maintain a list of the files in there by hand, in your source code, or, in a text file with a known name. Then, you can load that text file (with MainPage.class.getResourceAsStream("/all-image-names.txt") for example), and use the contents of it to know which file names will be available.
    2. Hack it, using various third party libraries. Note that these libraries fail in various circumstances. They work in the base case circumstance of having no modular or otherwise customized classloader infrastructure. Not recommended.
    3. Set up your build so that it produces this text file automatically during the build. After all, during the build (compilation) phase, the tools certainly do have that file listing.