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); 
有帮助吗?

解决方案

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!

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top