Question

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);
Was it helpful?

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.

OTHER TIPS

You should probably use ImageIcon.getImageLoadStatus() to make sure the image loaded without errors before attempting to render it on a JButton.

javas.swing.Action is a sort of ugly duckling class in Java GUI API: not much used and very few examples for correct use, despite its interesting proposal.

When using an Action in a button, you can define several properties you would usually have to add one by one directly to button instance, as the icon, tooltip, caption, etc.

An annoying issue is that Action overrides your button settings with a warning! So, if you use Action, avoid setting extra properties.

You can define your own Action factory class or extend AbstractAction and use putValue(String key, Object value) to set your button properties, as shown in the code snippet below.

Please, make sure you are using the keys defined in the Action class when setting your own values with putValues().

**
* Facility class for AbstractAction
* Remember that Action also extends ActionListener interface
*
*/
class MyAction extends AbstractAction {     
/**
 * Ctor.
 * @param name - The Action.NAME or the button caption
 * @param actionCMD - the Action.ACTION_COMMAND_KEY value
 * @param shortDescription - the tool tip, Action.SHORT_DESCRIPTION
 * @param icon - the default icon, or  Action.SMALL_ICON paramenter.
 */
public MyAction(String name, String actionCMD, String shortDescription, Icon icon) {                   
     putValue(Action.NAME, name);  
     putValue(Action.SHORT_DESCRIPTION, shortDescription);  
     putValue(Action.ACTION_COMMAND_KEY, actionCMD);  
     if(icon != null)
         putValue(Action.SMALL_ICON, icon);
 }  

 /**
  * The action to be performed
  */
 public void actionPerformed(ActionEvent e) {  
    // put your action code here
 }  
} // end class
 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top