Frage

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); 
War es hilfreich?

Lösung

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!

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top