本人想用几个JPanel的来重复合成一个图画,就是说,可以几层的JPanel来重叠在一起,然后想通过setOpaque的方法来设置每一个JPanel透明,想显示各个JPanel的图像,但是不行,请问怎样可以做到呢?
自己覆写JPanel的paintComponent方法,用Graphics的drawImage方法自己draw上去.
自己覆写JPanel的paintComponent方法,用Graphics的drawImage方法自己draw上去.
示例程序:
import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.*;/**
*author: [url=http://eastsun.javaeye.com]Eastsun[/url]
*/
public class CompositeImage extends JFrame{
Image backImage,foreImage;
public CompositeImage(){
super(\"CompositeImage\");
try{
backImage =ImageIO.read(new File(\"back.jpg\"));
foreImage =ImageIO.read(new File(\"fore.jpg\"));
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
JPanel panel =new JPanel(){
public void paintComponent(Graphics g){
Graphics2D g2 =(Graphics2D)g;
g2.drawImage(backImage,0,0,null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.3f));
g2.drawImage(foreImage,80,120,null);
}
};
Dimension dim =new Dimension(backImage.getWidth(null),backImage.getHeight(null));
panel.setPreferredSize(dim);
add(panel);
pack();
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new CompositeImage().setVisible(true);
}
});
}
}