1

I want to set a image icon to JButton, here the code that i tried:

public class Calculator {

    public static JFrame f;

    Calculator() throws IOException{

        JButton b;

        f = new JFrame();
        Image play = ImageIO.read(getClass().getResource("images/play.png"));
        b = new JButton(new ImageIcon(play));

        b.setBounds(250,250,75,20);

        f.add(b);
        f.setSize(500,500);
        f.setLayout(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws IOException {

        new Calculator();
    }
}

The program runs normally without errors, but the image didn't appear.

I think the image url is wrong.

I am using netbeans, so I created a folder named images in the source packages directory.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mohammad
  • 3,449
  • 6
  • 48
  • 75
  • Try and show the absolute path of your image in the program and compare it to actual path. Do they match? – LBes Oct 22 '15 at 12:22
  • 5
    `getClass().getResource("images/play.png")` Usually best to prefix the string with `/` like this `getClass().getResource("/images/play.png")` – Andrew Thompson Oct 22 '15 at 12:26
  • 2
    `f.setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Oct 22 '15 at 12:28
  • 1
    @AndrewThompson thank you, the problem solved by prefixing the string with the slash. – Mohammad Oct 22 '15 at 12:29
  • Glad you got it sorted. :) Now sort out those layouts. ;) – Andrew Thompson Oct 22 '15 at 12:30
  • Possible duplicate of [How do I add an image to a JButton](http://stackoverflow.com/questions/4801386/how-do-i-add-an-image-to-a-jbutton) – Petter Friberg Oct 22 '15 at 12:44

2 Answers2

1

Try with b.setIcon(new ImageIcon(getClass().getResource("images/play.png")));

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

The issue can be resolved by prefixing the resource path with a slash:

Image play = ImageIO.read(getClass().getResource("/images/play.png"));

This denotes that the image folder is at the root location of all resources and not relative to the current class location.

Credits partially go to Andrew Thompson's comment.

randers
  • 5,031
  • 5
  • 37
  • 64