这是我的代码,请帮助并解释我做错了什么,非常感谢。此外,我有点困惑线程是否我做得正确的方式。
public class Fade extends JPanel implements Runnable {
static Image image;
private float alpha = 0f;
static JFrame frame;
public static void main(String[] args) throws IOException {
image = new ImageIcon(ImageIO.read(new File("gummybear.jpg")))
.getImage();
frame = new JFrame("fade frame");
frame.add(new Fade());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(image.getWidth(frame), image.getHeight(frame));
// set picture in the center of screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable fade = new Fade();
executor.execute(fade);
// executor.shutdown();
// while (!executor.isTerminated()) {
// }
// System.out.println("Finished fade in / fade out threads");
}
public void run() {
while (alpha < 1) {
try {
System.out.println(alpha);
alpha += 0.1f;
this.repaint();
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Fader.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// SRC_OVER: If pixels in the source and the destination overlap, only
// the source
// pixels outside of the overlapping area are rendered. The pixels in
// the overlapping area are not changed.
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
alpha));
g2d.drawImage(image, 0, 0, null);
// Color c = new Color(255, 255, 255, alpha);
// g2d.setColor(c);
// g2d.fillRect(0, 0, image.getWidth(frame), image.getHeight(frame));
System.out.println("repaint");
}
}
图像填充
在我看来,您希望为从JPG文件加载的图像添加透明度。JPG文件没有alpha通道(用于透明度),因此这将不起作用。
您可以在Java教程之一中找到一个使用透明度(以及从JPG加载图像)的好例子:绘制图像
在这里,您可以找到一个很好的示例,其中的代码几乎可以满足您的要求:更改从JPG文件加载的图像的透明度。不同之处在于,不透明度值取自滑块控件,而不是定时变量。
螺纹材料
编辑:我刚刚意识到,您使用的是Swing,这是一种API,它不是为线程安全而设计的。
我只需要向您介绍Java教程如何在Swing中使用Swing定时器和并发性。
问题是您没有更改alpha
值。至少,不是您显示的Fade
实例的alpha
值:
// Here you are adding a "Fade" instance to the frame.
frame.add(new Fade());
...
// Here you are creating a NEW "Fade" instance. Only in
// this instance, the alpha value will be affected
Runnable fade = new Fade();
executor.execute(fade);
将其更改为
// Create a Fade instance and add it to the frame
Fade fade = new Fade();
frame.add(fade);
...
// Submit the SAME Fade instance to the executor
executor.execute(fade);
您还必须验证alpha
值是否保持在[0,1]中,但这可以通过类似的方法来完成
alpha += 0.1f;
alpha = Math.min(1.0f, alpha);