Reputation: 446
I have two Icons which one of them has a .gif
as an Icon, and the other a .png
. So I would like to combine this icons to put the animated one above the other.
This code works with static
Icons, but at time to put an animated
one, it doesn´t print the animated.
public class Combine implements Icon{
private final Icon back;
private final Icon front;
public Combine(Icon pBack, Icon pFront) {
this.back= pBack;
this.front= pFront;
}
@Override
public int getIconHeight() {
return Math.max(front.getIconHeight(), back.getIconHeight());
}
@Override
public int getIconWidth() {
return Math.max(front.getIconWidth(), back.getIconWidth());
}
@Override
public void paintIcon(Component arg0, Graphics arg1, int arg2, int arg3) {
back.paintIcon(arg0, arg1, arg2, arg3);
front.paintIcon(arg0, arg1, arg2, arg3);
}
}
I am loading the icons using this:
Icon back = new ImageIcon(Toolkit.getDefaultToolkit().createImage(MyClass.class.getResource(source)));
Icon front = new ImageIcon(Toolkit.getDefaultToolkit().createImage(MyClass.class.getResource(source)));
EDIT:
I want to use the icon for a JButton icon.
Upvotes: 0
Views: 120
Reputation: 44404
You need to tell the animated ImageIcon to notify the JButton whenever a new frame becomes available:
front.setImageObserver(button);
See ImageIcon.setImageObserver for details.
By the way, ImageIcon has a constructor that takes a URL:
ImageIcon back = new ImageIcon(MyClass.class.getResource(backSource));
ImageIcon front = new ImageIcon(MyClass.class.getResource(frontSource));
Upvotes: 1
Reputation: 324147
one of them has a .gif as an Icon,
I think you need to use a JLabel to have the animation. That is the JLabel is responsible for repainting the Icon as it animates.
Try just displaying the two Icons in two JLabels:
JLabel front = new JLabel( new ImageIcon(...) );
JLabel back = new JLabel( new ImageIcon(...) );
back.setLayout( new GridBagLayout() );
back.add(front, new GridBagConstraints());
The front icon should be centered on the back icon.
You may also want to check out Compound Icon which is a more flexible version of your class that allows you to combine 2 or more Icons into one.
Upvotes: 1