问题
I was wondering if it were possible to layer ImageIcons in Java. I will be working with GIF images, and will have a grid of ImageIcons representing the "background" of my JPane.
When a certain condition is true, I need to be able to add an image that has transparency on top of the other image.
Regards, Jack Hunt
回答1:
yes that's possible and there are two correct ways
1) if is there only one Image then put JLabel with Icon to the GlassPane
2) use LayeredPane for <= Java6 (not Java7 user there is JLayer)
回答2:
You could simply use g.drawImage(...)
to draw them onto the panel in an overriden paintComponent
method. That would be the easiest way to do that.
Because your question mentions ImageIcon
, it would be correct to use it if your gif's are animated. Otherwise, BufferedImage
is generally preferred. If you decide to keep to ImageIcon
, you should use paintIcon(Component c, Graphics g, int x, int y)
instead of g.drawImage(...)
.
If you want to add images dynamically, consider storing them in an array or ArrayList
, then simply iterate through the array / list in your paintComponent
.
For example:
JPanel panel = new JPanel(){
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
if(yourCondition){
g.drawImage(img, x, y, this); // for example.
}
}
};
The other alternative is to create a private class which extends JPanel. For example:
public class OuterClass{
// fields, constructors, methods etc..
private class MyPanel extends JPanel{
// fields, constructors, methods etc..
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
if(yourCondition){
g.drawImage(img, x, y, this); // for example.
}
}
}
}
Side note: Any particular reason why you need to use GIF? PNG is generally better.
EDIT: (according to Andrew Thompson's idea)
In order to take a snapshot of all the images contained in the background...
A variant of the following idea:
BufferedImage background;
public void captureBackground(){
BufferedImage img = GraphicsConfiguration.createCompatibleImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
for(ImageIcon i : imageIconArray){ // could be for(BufferedImage i : imageArray){
i.paintIcon(this, g, 0, 0); // g.drawImage(i, 0, 0, null);
}
g.dispose();
background = img;
// either paint 'background' or add it to your background panel here.
}
回答3:
You can use the modes of AlphaComposite to achieve a variety of effects. There's an example and utility here.
Addendum: Note that the default composite mode for a platform's concrete implementation of Graphics2D is AlphaComposite.SRC_OVER, which may or may not be what you want.
回答4:
You could use the Overlay Layout to stack JLabels on top of one another.
Or you could use the Compound Icon to stack icons on top of one another.
来源:https://stackoverflow.com/questions/9227270/possible-to-layer-imageicons