3

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

4

4 回答 4

5

是的,这是可能的,有两种正确的方法

1)如果只有一个图像,则将带有图标JLabel放入GlassPane

2) 对 <= Java6 使用LayeredPane(不是 Java7 用户有 JLayer)

于 2012-02-10T11:52:27.190 回答
5

您可以简单地使用覆盖方法g.drawImage(...)将它们绘制到面板上。paintComponent那将是最简单的方法。

因为您的问题提到ImageIcon了 ,所以如果您的 gif 是动画的,则使用它是正确的。否则,BufferedImage通常是首选。如果您决定坚持ImageIcon使用 ,则应使用paintIcon(Component c, Graphics g, int x, int y)代替g.drawImage(...)

如果要动态添加图像,请考虑将它们存储在数组或ArrayList中,然后简单地遍历paintComponent.

例如:

JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
       super.paintComponent(g);
       if(yourCondition){
           g.drawImage(img, x, y, this); // for example.
       }
    }
};

另一种选择是创建一个扩展 JPanel 的私有类。例如:

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.
          }
       }

    }
}

旁注:您需要使用 GIF 的任何特殊原因?PNG通常更好。

编辑:(根据安德鲁汤普森的想法)

为了拍摄背景中包含的所有图像的快照......
以下想法的变体:

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.
}
于 2012-02-10T11:49:59.527 回答
4

您可以使用Overlay Layout将 JLabels 堆叠在一起。

或者您可以使用复合图标将图标堆叠在一起。

于 2012-02-10T16:16:50.507 回答
4

您可以使用 的模式AlphaComposite来实现各种效果。这里有一个示例和实用程序。

附录:请注意,平台具体实现的默认复合模式Graphics2DAlphaComposite.SRC_OVER,这可能是也可能不是您想要的。

于 2012-02-10T11:50:26.880 回答