I created a new class CellPanel which expands JPanel (it uses GridBagLayout()). The JFrame has GridLayout() and size 640x480. In CellPanel I add class FadeIn which expands JPanel. FadeIn has this fade in and out effect but the image that is fading in/out is very small in this particular case, otherwise it works fine.
Class FadeIn:
public FadeIn(Image image) {
imagem = image;
timer = new Timer(50, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,alpha));
g.drawImage(imagem,0,0,getWidth(),getHeight(),this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(fade == false)
{
alpha += 0.05f;
if (alpha >1) {
alpha = 1;
fade = true;
}
repaint();
}
else if(fade == true)
{
alpha -= 0.05f;
if (alpha <0) {
alpha = 0;
fade = false;
}
repaint();
}
}
The code where I'm using these classes:
JFrame dialog = new JFrame();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setSize(640, 480);
dialog.setResizable(false);
dialog.setLocationRelativeTo(null);
dialog.setLayout(new GridLayout(5,5));
cell = new CellPanel(ground.getImage());
cell.setLayout(new GridBagLayout());
iconSolver = new ImageIcon("Resurse/fadingRight.png");
fade = new FadeIn(iconSolver.getImage());
fade.setSize(iconSolver.getIconWidth(), iconSolver.getIconHeight());
fade.setOpaque(false);
cell.add(fade);
cell.setSize(dialog.getWidth()/5,dialog.getWidth()/5);
dialog.getContentPane().add(cell);
dialog.setVisible(true);