Question

I have a question and I know it may seem simple but I spent 3 hours and still I am having trouble:

I am trying to add and remove image in Jlabel in java dynamically I am trying this code but I cant see any image loding on label what is wrong with my code and what can I do else?

public static void main (String[] args)
{
    ImageIcon icon = new ImageIcon ("1.gif");
    JFrame frame = new JFrame ("Nested Panels");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    // Set up first subpanel
    JPanel subPanel1 = new JPanel();
    subPanel1.setPreferredSize (new Dimension(450, 100));
    //subPanel1.setBackground (Color.green);
    JLabel label1 ;
    label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);
    label1.setHorizontalTextPosition (SwingConstants.LEFT);
    label1.setVerticalTextPosition (SwingConstants.BOTTOM);
    subPanel1.add (label1);
    JPanel primary = new JPanel();
    primary.setBackground (Color.blue);
    primary.add (subPanel1);
    frame.getContentPane().add(primary);
    frame.pack();
    frame.setVisible(true);
}
Was it helpful?

Solution

ImageIcon(String) assumes that the value is a File.

If the image is stored within the context of the Jar (or project if you're using NetBeans), then you will need to access the image via Java's resource management API, for example.

ImageIcon icon = new ImageIcon (YourProject.class.getResource("1.gif"));

If you're using Eclipse, the resource will need to be stored within the projects resource folder.

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