Question

I am trying to set a JFrame imageIcon and for some reason it is not displaying in the JFrame.

  ImageIcon img  = new ImageIcon("stop.jpg");

  frame.setIconImage(img.getImage());

I create an ImageIcon variable and then uses that variable to getImage() and it does not work. Is there a reason that it does not work?

Question: Why does the ImageIcon not work?

Class:

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import java.awt.Toolkit;

public class TestMenu extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel myPanel;

    private static void setLookFeel() {
         try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
         } catch (Exception ex) { }
    }

    public static void main(String[] args) {
        setLookFeel();
        ImageIcon img  = new ImageIcon("stop.jpg");
        TestMenu frame = new TestMenu();
        frame.setIconImage(img.getImage());
        frame.setVisible(true);
    }

    public TestMenu() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu mnNewMenu = new JMenu("TestA");
        menuBar.add(mnNewMenu);

        JMenuItem Item1 = new JMenuItem("TestAA");
        Item1.addActionListener(new MyMenuListener(Item1));
        mnNewMenu.add(Item1);

        JMenu Item2 = new JMenu("TestB");
        menuBar.add(Item2);

        JMenu Item3 = new JMenu("TestBB");
        Item2.add(Item3);

        JMenuItem Item4 = new JMenuItem("TestBB-B");
        Item4.addActionListener(new MyMenuListener(Item4));
        Item3.add(Item4);

        myPanel = new JPanel();
        myPanel.setBorder(new EmptyBorder(25, 25, 25, 25));
        myPanel.setLayout(new BorderLayout(10, 10));
        setContentPane(myPanel);
    }
}
Was it helpful?

Solution 2

Where is your image saved? It is possible the path to your image is not correct:

ImageIcon img  = new ImageIcon("stop.jpg");

You should use a path that is based on your class. Here for example the image is stored in the package images.

new ImageIcon(MyClass.class.getResource("/images/image.png"));

OTHER TIPS

It wors fine for me, check:

1. The name of your image (Java is case sensitive) i.e. Stop.jpg instead of stop.jpg

2. The path of your image (Maybe it's not in the same folder). i.e."../images/stop.jpg" or "/images/stop.jpg"

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top