I want to have an image fade in onto a panel that is part of a card layout. When i'm at a certain place in the program, this panel will show on top and I then want the image to be loaded in with a fade-in effect. This is a big project so I will only paste the relevant code.
I have a GUI class which contains the jFrame, all the jPanels etc. When a certain event is triggered, this code runs:
cardMain.show(pMain, "cLeprechaun");
FadeIn.run(pLeprechaun);
It loads up the correct panel and then runs a static method in the FadeIn class, that is supposed to add the image onto the panel pLeprechaun.
Here is the FadeIn class:
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FadeIn extends JPanel implements ActionListener {
Image imagem;
Timer timer;
private float alpha = 0f;
public FadeIn() {
imagem = new ImageIcon("darkforest.jpg").getImage();
timer = new Timer(100, this);
timer.start();
}
// here you define alpha 0f to 1f
public FadeIn(float alpha) {
imagem = new ImageIcon("darkforest.jpg").getImage();
this.alpha = alpha;
}
@Override
public void paintComponent(Graphics g) {
System.out.println("paint");
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
alpha));
g2d.drawImage(imagem, 0, 0, null);
}
public static void run(JPanel jPanel) {
jPanel.add(new FadeIn());
}
public void actionPerformed(ActionEvent e) {
alpha += 0.05f;
if (alpha >1) {
alpha = 1;
timer.stop();
}
repaint();
}
}
Nothing happens, no image is show on the panel. Just to try it out, instead of jPanel.add(new FadeIn()); I have also tried to create a new jFrame and adding a new FadeIn onto that, and it works then. Of course, instead of an image being painted on the jPanel, a new jFrame pops up ontop of the main one, with the image nicely fading in. But that's not what I want happening.
Is there a way to solve this?