not able to give image to button

2019-08-01 03:05发布

问题:

I am new to Swing. I need to give a Jbutton an icon. I found example code so many places and tried like this

ImageIcon cup = new ImageIcon("/home/Whether/Picture/start.png");
JButton startBut=new JButton(cup);
panel.add(startBut);

But button is showing without Icon.Image path is correct.

Pls coorect me if Im wrong?

Thnx in advance

回答1:

The best way of adding images is to link image to an "anchor" java class

Create "Anchor" class as a source bound and place it into your project package which contains an "image.png" etc... So you can read image right from the Jar file as

Image image=ImageIO.read(Anchor.class.getClassLoader().getResourseAsStream("image.png"));
ImageIcon icon=new ImageIcon(image);

Rest things with JButton I guess you know :)

Good luck