user819774
user819774

Reputation: 1514

Image doesn't show in image button

I have create an image button but it didn’t show the image. The file is on src\MyPackage folder. How can I map it?

There is my code:

jpAnnotation=new JPanel();     

jpAnnotation.setLayout(new FlowLayout(FlowLayout.LEADING));
JButton btnUnderline =new JButton(new ImageIcon ("UnderlineIcon.gif"));
btnUnderline.setSize(50, 260);
btnUnderline.setAlignmentX(JButton.LEFT_ALIGNMENT);
btnUnderline.setHorizontalAlignment(JButton.LEFT);
btnUnderline.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent arg0){                      
         ActionEvent ae = new ActionEvent(bean, 0, "Underline");
         bean.actionPerformed(ae);
    }
});
jpAnnotation.add(btnUnderline); 

Upvotes: 0

Views: 274

Answers (2)

PrR3
PrR3

Reputation: 1246

Just a little code snippet:

btnUnderline.setIcon(
  new ImageIcon(getClass().getResource("/path/to/UnderlineIcon.gif")));

Brief explanation

Using this statement for loading your image, you don't have to care about the right URL to your file, because you automatically get the correct URL.

This is based on loading the resource from the class path and not from the filesystem path!

Upvotes: 3

Zyn
Zyn

Reputation: 614

Try this:

btnUnderline.setIcon( new ImageIcon( "C:\\YourFolder\src\MyPackage\UnderlineIcon.gif" ) );

If of course you're using Windows. Alternatively you can move the gif to the same directory as where you're executing your code from.

Upvotes: 1

Related Questions