Search code examples
javaeclipseimageswingjar

Unformatted image when exporting Eclipse JAR


When Export - Runnable Jar the image of the frame loses its formatting. See in the image Screen 1 is the window executed directly in the eclipse, Screen 2 is the execution of Jar. enter image description here

Code where the image is inserted.

    JLabel lblImage = new JLabel();
    lblImage.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    lblImage.setBounds(225, 25, 225, 225);
    lblImage.setIcon(new ImageIcon("logo.png"));

Code automatically generated by windows builder for adding lblimagem to the frame:

GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(
        gl_contentPane.createParallelGroup(Alignment.TRAILING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblImage, GroupLayout.PREFERRED_SIZE, 225, GroupLayout.PREFERRED_SIZE)
                        .addGap(38)
                        .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                            .addComponent(lblTextApresentation, GroupLayout.PREFERRED_SIZE, 424, GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblVersions)
                            .addComponent(cbVersions, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                    .addGroup(gl_contentPane.createSequentialGroup()
                        .addGap(199)
                        .addComponent(lblTsvizzevolution, GroupLayout.PREFERRED_SIZE, 208, GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
    );

Solution

  • new ImageIcon("logo.png")

    as per the javadoc, that parameter is called filename.

    Focus on the 'file' part of that: entries in jar files aren't files and therefore, what you want is impossible with this constructor. You'll have to use something else.

    What you're looking for is the getResource system: This asks java to give you stuff from the same location that java is loading your class files. Even if that is in a jar.

    URL url = MyClass.class.getResource("logo.png");
    new ImageIcon(url);
    

    is all you need. The parameter to getResource is ordinarily relative to wherever MyClass.class might be. If you instead want to go relative to the 'root' of the jar, use /logo.png instead. This also works during development, and works when you deploy this stuff. No matter how you deploy it.