image not loading java

26 Views Asked by At

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.");
            }
        });
    }
}

0

There are 0 best solutions below