Search code examples
javaimageswingembedded-resourceimageicon

icon in JTabbedPane is not shown


I have a problem with my tabs:

JTabbedPane tab = new JTabbedPane();
    frame.add(tab, BorderLayout.CENTER);

    JPanel contact = new JPanel();
    contact.add(backgroundContact);
    tab.add("Contacto", contact);
    //tab.addTab("Contacto",new ImageIcon("images/image2.gif"), contact,"");

    JPanel schedule = new JPanel();
    schedule.add(backgroundSchedule);
    tab.add("Horario", schedule);
    //tab.addTab("Horario", new ImageIcon("images/image2.gif"), schedule,"");

    JPanel cost = new JPanel();
    cost.add(backgroundCost);
    tab.add("Tarifas", cost);
    //tab.addTab("Tarifas", new ImageIcon("images/image3.gif"), cost,"");


      // Los iconos
    tab.setIconAt(0, new ImageIcon("images/image1.gif"));
    tab.setIconAt(1, new ImageIcon("images/image2.gif"));
    tab.setIconAt(2, new ImageIcon("images/image3.gif"));

I've tried both options, but the icons are not shown. Why is it happening?

I also tried: new ImageIcon("images/im.gif") which doesn't exist and I haven any error


Solution

  • Try this instead:

    URL urlToImage3 = this.getClass().getResource("/" + "images/image3.gif");
    ... new ImageIcon(urlToImage3);
    

    You might concatenate "/" + "images/image3.gif" - I just wanted to highlight the leading /, since it is more robust to search from the root of the class-path.

    If these images are an 'embedded resource' as I suspect, they will not be available by File at run-time, but should be on the class-path in one of the Jars of the app., and therefore available by URL.