0

So im trying to get a specified image as the "look" of the Jbutton but it just isnt working. any ideas?

The code:

JButton btnClose = new JButton("Close");
    try {
        Image img = ImageIO.read(Window.class.getResource("resources/quit_button.bmp"));
        btnClose.setIcon(new ImageIcon(img));
      } catch (IOException ex) {
      }

btnClose.setVisible(true);
btnClose.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        frame.dispose();
    }
});

My image path is: C:\Users\ *User*\workspace\Pede\pede_Exe\resources\quit_button.bmp

  • Window is your class? – m.cekiera May 13 '15 at 19:00
  • Yes it is, should that give issues? – Jim de Vries May 13 '15 at 19:01
  • nope, just asking ... meaby you should check what is exactly you class path by `ClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath()` and check is your path to file correct – m.cekiera May 13 '15 at 19:09
  • What is the package of your class? What directories are in the classpath? Your code tries to load an image from the classpath, located in the sub-package resources of your Window class's package. – JB Nizet May 13 '15 at 19:35

1 Answers1

1

"Isn't working" isn't a lot to go on, but my suspicion is that ImageIO is throwing an exception before setting the icon. This is often (but not exclusively) because your path is wrong.

First and foremost, print your stack trace. That should be, for you,

ex.printStackTrace();

in your catch block. That stack trace is an arrow to the problematic code, and often has a plain-English explanation attached to it. Get in the habit, you won't regret it.

Second, see to it that you're looking in the right place for your image. The easiest way to do this can be found here: Find where java class is loaded from

As you can see, there are a lot of possibilities. If the path of your class, compounded with the path of your resource, is not a real thing, then ImageIO will not find your icon.

Community
  • 1
  • 1
Michael Macha
  • 1,729
  • 1
  • 16
  • 25