0

i am trying to load an image to a JButton for display but it doesnt load the image is in src folder of the project and its the same type here is the code.


import javax.swing.*;
import java.awt.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ImageIcon icon = new ImageIcon("asa.jpg");

            // Check if the image was loaded successfully
            if (icon.getImageLoadStatus() == MediaTracker.COMPLETE) {
                // Create a label with the loaded image
                JLabel label = new JLabel(icon);

                JFrame frame = new JFrame("Image Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(label);
                frame.pack();
                frame.setLocationRelativeTo(null); // Center the frame on the screen
                frame.setVisible(true);
            } else {
                System.err.println("Error loading the image.");
            }
        });
    }
}

SpyrosGew
  • 1
  • 1
  • 2
    *the image is in src folder of the project* - the image should be contained in a directory found on your classpath. You should NOT use ImageIcon to read the image. Instead you should be using `ImageIO`. You will get an Exception when the image is not found. – camickr Jul 28 '23 at 21:17
  • Many IDEs and build systems will automatically incorporate resources in the `src` file into the resulting "bundle". This means they are no longer accessible as "files" (which `ImageIcon(String)` is expecting). Instead you need to use `Class#getResource` to obtain a `URL` reference to them – MadProgrammer Jul 29 '23 at 00:42

0 Answers0