Problems with ImageIcon

0

Hello this is the exercise 9.8 of How to Schedule in JAVA of Deitel Edition 10 I can not see the icon "GUItip.gif" displayed

This is how the GIF is stored

Here next to the two labels should appear the gif

this is the GIF

import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;



public class GUIJLabel {


public static void main(String[] args) {
  //crea una etiqueta con texto solamente
  JLabel etiquetaNorte = new JLabel("Norte");  

  //crea un icono a partir de una imagen para poder colocarla en un objeto
ImageIcon etiquetaIcono = new ImageIcon("GUItip.gif");

//crea una etiqueta con un icono en vez de texto
JLabel etiquetaCentro = new JLabel(etiquetaIcono);

//crea otra etiqueta con un icono
JLabel etiquetaSur = new JLabel(etiquetaIcono);

//establece la etiqueta para mostrar texto(asi como un icono)
etiquetaSur.setText("Sur");

//crea un marco para contener las etiquetas
JFrame aplicacion = new JFrame();
aplicacion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//agrega las etiquetas al marco;el segundo argumento especifica
//en que parte del marco se va a agregar la etiqueta
aplicacion.add(etiquetaNorte,BorderLayout.NORTH);
aplicacion.add(etiquetaCentro,BorderLayout.CENTER);
aplicacion.add(etiquetaSur,BorderLayout.SOUTH);


  aplicacion.setSize(400,400);
  aplicacion.setVisible(true);
  }

}
    
asked by Masterweed 10.03.2018 в 20:06
source

1 answer

1

This is a path error to get the image itself, simply doing ImageIcon etiquetaIcono = new ImageIcon("GUItip.gif"); what it does is to look for the image file in the root folder of your project, but according to the image this is not so. Which having this clear two solutions arise

  • Move the image to the root folder of your project if NetBeans is secure in C:\Users\TUUSUARIO\Documents\NetBeansProjects\NombreProyecto
  • Obtaining the resource of a package as the image shows would be necessary to use getResource and access its image, (Note that this will work only if the class and the image are in the same package, as is the case with your example) , Ejm

    URL urlimagen = GUIJLabel.class.getResource("GUItip.gif");
    //crea un icono a partir de una imagen para poder colocarla en un objeto
    ImageIcon etiquetaIcono = new ImageIcon(urlimagen);
    
answered by 10.03.2018 / 20:46
source