我正在尝试制作一个通常演示 src_in AlphaComposite 的应用程序。我需要的输出是:-
但我得到以下输出: -
我在哪里做错了?这是我的完整代码。
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SrcInDemo extends JFrame{
private JCheckBox jcb;
SrcInDemo()
{
super("SrcIn Demonstration");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
add(new comp(),BorderLayout.CENTER);
setVisible(true);
add(jcb=new JCheckBox("Shadow"),BorderLayout.SOUTH);
jcb.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
repaint();
}});
}
class comp extends JComponent
{
private BufferedImage image,landscape;
comp()
{
try{
image=ImageIO.read(/*getClass().getResource("picture.png")*/new File("src/picture.png"));
landscape=ImageIO.read(/*getClass().getResource("landscape.jpg")*/new File("src/landscape.jpg"));
}catch(IOException e){System.out.printf("error loading image");}
}
public void paintComponent(Graphics g)
{
//The following commented lines were there in the original code of Filthy Rich Clients
//But I have removed them as it was supposed to create a back image.I have created g2
//directly.
/* BufferedImage temp = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = temp.createGraphics();*/
Graphics2D g2=(Graphics2D)g.create();
if(jcb.isSelected())
{
int x=(getWidth()-image.getWidth())/2;
int y=(getHeight()-image.getHeight())/2;
g2.drawImage(image,x+4,y+4,null);
Composite oldComposite=g2.getComposite();
g2.setComposite(AlphaComposite.SrcIn);
g2.setColor(Color.BLACK);
g2.fillRect(0,0,getWidth(),getHeight());
g2.setComposite(oldComposite);
g2.drawImage(image,x,y,null);
}
else
{
int x=(getWidth()-image.getWidth())/2;
int y=(getHeight()-image.getHeight())/2;
g2.drawImage(image,x,y,null);
Composite oldComposite=g2.getComposite();
g2.setComposite(AlphaComposite.SrcIn);
g2.drawImage(landscape,x,y,null);
g2.setComposite(oldComposite);
}
//g.drawImage(temp, 0, 0, null);
}
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new SrcInDemo();}});
}
}