Is there an alternative to getClass().getResource() for a Static ImageIcon
Asked Answered
C

1

7

Ok so I got a static ImageIcon and the Image just doesn't show up. In the same program I use other ImagesIcon but they are not static so when I declare them I do it like this:

public ImageIcon blabla = new ImageIcon(getClass().getResource(blabla.png)); 

But if I declare a ImageIcon Static I cannot use that line since one cannot get acces to getClass() from a static value. Right now those images are not showing up using this:

public static ImageIcon blabla = new ImageIcon(blabla.png); 

Thanks for your help!

public static ImageIcon networkOfflineIcon = new ImageIcon("Images/networkOfflineIcon.png");
public static ImageIcon networkIcon = new ImageIcon("Images/networkIcon.png");
protected static JMenuItem jmiRemote = new JMenuItem("  Remote", networkOfflineIcon);
//************************************************************************
public static void changeNetWorkStatus(boolean network_status)          
//************************************************************************
{
    if(network_status){
        Application.jmiRemote.setIcon(networkIcon);
        Application.jmiRemote.setText("NetWork Online/Remote is On");
        Application.lockScreenRemote();

    }else if(!network_status){
        Application.jmiRemote.setIcon(networkOfflineIcon);
        Application.jmiRemote.setText("NetWork Offline/Remote is Off");
        Application.unlockScreenRemote();
    }
}//DOESNT CHANGE THE IMAGE
//************************************************************************
Coreencorel answered 24/5, 2012 at 15:58 Comment(1)
Try to avoid stuff like if (t == true) and if (t == false), use if (t) and if( ! t ) instead.Wilcher
W
4

In a static context, you can write:

public ImageIcon imageIcon = new ImageIcon(MyClass.class.getResource("icon.png"));

Or, alternatively try ImageIO.read(new File("icon.png"))

Wilcher answered 24/5, 2012 at 16:2 Comment(2)
Works fine now thank you for the fast fix i will also avoid (t == true)Coreencorel
ImageIO.read is not the best suggestion since you then need to handle the exceptions that it throws. I would stick with the first suggestion and use MyClass.class.Coburn

© 2022 - 2024 — McMap. All rights reserved.