Home > Software engineering >  Why doesn’t this ImageIcon show up?
Why doesn’t this ImageIcon show up?

Time:08-25

I tried everything, but the image won't show up, I tried to make the image smaller but it was useless, I tried to change the paths, I tried to change the position of the image but it didn't help, I tried to search on the internet but nothing.

What I see is just the blank GUI, without the text and without the image. If you could help me, you would do me a great pleasure.

Here is the code:

package main;

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

public class Main {
    public static void main(String[] args) {
        // Creating a new frame
        GFrame frame = new GFrame("JFrame",true);
        frame.lock(true);

        // Setting the size of the frame
        frame.setSize(500, 500);

        // Creating images
        ImageIcon icon = new ImageIcon("src/main/img.png");
        frame.setIconImage(icon.getImage());

        // Creating labels
        JLabel title = new JLabel("A java GUI!",icon,0);
        title.setVerticalAlignment(1);
        title.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,30));

        // Adding the labels
        frame.add(title);

        // Stopping the program if the frame gets closed
        frame.onCloseExit(true);
    }

    public static Image getScaledImage(Image srcImg, int w, int h){
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = resizedImg.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();

        return resizedImg;
    }
}

CodePudding user response:

I put setVisible(true) at the bottom of the code, and now it works, I'm kinda stupid, because I remembered it later. Thanks for making me remember.

  • Related