jessechk
jessechk

Reputation: 450

Custom JButton subclass setIcon method not working

EDIT: This is a Netbeans project. So I have created a subclass of JButton called Card. I am trying to set an icon to the button on creation.

package matchinggame;

public class Card extends JButton {

    final static ImageIcon defaultIcon = new ImageIcon("cardback.jpg");

    ...

    public Card(int secretIconIndex) { 
        //Set the button's icon to the default icon
        setIcon(defaultIcon);
        ... 
    }

    ...

}

If you were wondering, the location of the "cardback.jpg" image is:

C:\Users\Jesse\SkyDrive\Documents\RCS\Grade 12\ICS4U\M9\MatchingGame\src\matchinggame\cardback.jpg

It is in the same folder/package as all the classes, so I believe I can leave the relative filepath like that. When I run the program, all the buttons are just blank (no text or icon). Is this a constructor issue or filepath issue?

Upvotes: 1

Views: 2924

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48620

If this is an Eclipse project store the image in a resources/ folder in the src/ folder.

setButtonIcon("cardback.jpg");

public void setButtonIcon(String filename) {
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  InputStream input = classLoader.getResourceAsStream("/"+filename);
  ImageIcon icon = new ImageIcon(ImageIO.read(input));
  super.setIcon(icon);
}

Upvotes: 4

jessechk
jessechk

Reputation: 450

My question was answered in the question comments. brano88 and Hovercraft Full of Eels said to use resources instead of file paths. The following fixed my problem:

final ImageIcon defaultIcon = new ImageIcon(getClass().getResource("/resources/cardback.jpg"));

I put this in my Card class.

Note: I moved my images to a new "resources" package inside the "src" folder in Eclipse or "Source Packages" folder in Netbeans.

Upvotes: 1

Edgard Leal
Edgard Leal

Reputation: 2720

If using the "eclipse" the image must be inside the folder "src" to use an absolute path. Use:
new File("cardback.jpg").exists() // to see if the file is in the right place

Upvotes: 0

Related Questions