0

My icon wont show up, I had this problem before even with images on labels.

import javax.swing.*;

public class Main {

    public static void main(String[] args){
        JFrame frame1 = new JFrame();
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setSize(600,600);
        frame1.setVisible(true);

        ImageIcon image1 = new ImageIcon("n.png");
        frame1.setIconImage(image1.getImage());
    }
}

Found the solution for JFrame Icon and JLabel icon: MyFrame as separated class

import java.awt.*;

public class MyFrame extends JFrame {
    MyFrame(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(600,600);
        this.setIconImage(new ImageIcon(getClass().getResource("p.PNG")).getImage());
        this.getContentPane().setBackground(new Color(136,51,240));
    }
}

MyLabel also separated:

import javax.swing.*;

public class MyLabel extends JLabel {
    MyLabel(){
        this.setText("Random generic text..");
        this.setSize(200,200);
        this.setIcon(new ImageIcon(getClass().getResource("P.PNG")));
    }

}

Main:

public class Main {
    public static void main(String[] args){

        MyFrame frame1 = new MyFrame();
        MyLabel label1 = new MyLabel();
        frame1.add(label1);
        frame1.setVisible(true);

    }
}
Adrian M
  • 9
  • 4
  • Maybe the frame is rendered, when you call setVisible(true). Thus adding the icon after rendering won't show it unless you either force a re-rendering or set the icon prior to initial rendering. – RainerZufall Jul 01 '22 at 09:32
  • 1
    @RainerZufall *"Maybe .."* Nope. The icon for a frame can be changed at any time. Visible, invisible, doesn't matter. – Andrew Thompson Jul 01 '22 at 10:52
  • 2
    @AndrewThompson Thanks I analyzed mentioned post and getResource method so my JFrame and also JLabel icon from my other post now are working properly – Adrian M Jul 01 '22 at 12:31
  • *"working properly"* Glad you got it sorted. :) – Andrew Thompson Jul 01 '22 at 13:06

0 Answers0