Making a fade transition using JPanels

94 views Asked by At

Is there any way to make a fade animation between two JPanels? I am trying to transition the loading screen into the main menu of the game, this occurs when the loading is fully complete. But for some reason it stays black (the color of first JPanel) Here is the code I have come up with ->

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DisplayWindow implements Runnable{
    
    public JFrame frame = new JFrame();
    public Thread loop = new Thread(this);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new DisplayWindow());
    }
    
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    private int transparency = 255;

    public DisplayWindow() {
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel2);
        frame.add(panel1); //Overlays panel2
        frame.pack();
        frame.setSize(800,500);
        frame.setVisible(true);
        loop.start();
    }
    @Override
    public void run() {
        while(loop != null) {
            panel1.repaint();
            panel2.repaint();
            panel1.setBackground(new Color(0, 0, 0, transparency));
            
            if(transparency > 0) transparency--; //decrements transparency each time the loop is run
            
            try {Thread.sleep(16);} 
            catch (InterruptedException e) {e.printStackTrace();}
        }
    }
}
0

There are 0 answers