How to upload files from the JAR

1

Hello friends, I have a code for a program that changes the color window and has 3 buttons with an icon or image but I really do not understand why the images do not appear in the JAR, I have the images in the src folder and in sources packages this is a package with my classes and the main one and another is default packages, there are my images, in netbeans it works perfectly. When I unzip my JAR if there are the images but when executing it nothing! someone to help me please.

These lines are responsible for putting the icon on a button, use the library swing.ImageIcon :

AccionColor accionAmarillo=new AccionColor("Amarillo", new ImageIcon("src/amarillo.jpg"), Color.YELLOW);
AccionColor accionAzul=new AccionColor("Azul    ", new ImageIcon("src/azul.jpg"), Color.BLUE);
AccionColor accionRojo=new AccionColor("Rojo     ", new ImageIcon("src/rojo.jpg"), Color.RED);
    
asked by pseudoprogramador 18.06.2017 в 23:51
source

2 answers

2

You can not use the relative path because your images are in the jar, and when using the relative path you are taking the path of work directory or the path from where the jar was executed, you can see it by printing System.getProperty("user.dir") .

What you have to do is use the getResource method:

ImageIcon icon = new ImageIcon(getClass().getResource("/amarillo.jpg"));
    
answered by 19.06.2017 в 00:35
0

If you want to upload a file contained in a .jar file, it can be done in this way if you need a BufferedReader :

InputStream in = getClass().getResourceAsStream("/amarillo.jpg"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

or in this way if you need to load the file within ImageIcon :

ImageIcon icon = new ImageIcon(getClass().getResource("/amarillo.jpg"));

Example:

AccionColor accionAmarillo=new AccionColor("Amarillo", new ImageIcon(getClass().getResource("/amarillo.jpg")), Color.YELLOW);
    
answered by 20.06.2017 в 00:05