Search code examples
javauser-interfacejbuttonpackagingimageicon

Image Icon not showing on JButton


I'm currently making a game in java and have a JButton which has an image icon. The only problem is the image is not shown and not even an error is thrown in the debug window.

I have packaged my program (see screenshot - https://db.tt/N9CwHJdf). The code I have used is written below, if anyone could resolve this problem I'd really appreciate it. Thank you.

//Button Image
ImageIcon diceIcon = new ImageIcon("Client/images/DiceIcon.png");

//Create Button
JButton rollDice = new JButton("Roll Dice", diceIcon);
rollDice.setForeground(Color.darkGray);
rollDice.setFocusPainted(false);
rollDice.setPreferredSize(new Dimension(284,50));
rollDice.setBorder(BorderFactory.createLineBorder(Color.orange));
rollDice.setBackground(Color.orange);
rollDice.setToolTipText("Click to roll dice and continue playing");
rollDice.addActionListener(this);

Solution

  • You can load your ImageIcon like this:

    ImageIcon diceIcon = new ImageIcon(getClass().getResource("/images/DiceIcon.png"));
    

    Read the Java Tutorial on How to Use Icons for more.