Java JFrame create transparent window opacity animation
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Main extends JPanel { JFrame frameParent;//from ww w . j a v a 2 s .com boolean focusWindow = false; private static float EXIT_WINDOW_OPACITY = .60f; public Main() { final JButton animButton = new JButton("<html><font size=+2>Press Me!</font>"); animButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); add(animButton); } public void apply(JFrame frame) { frameParent = frame; frame.setUndecorated(true); frame.setOpacity(EXIT_WINDOW_OPACITY); frame.addMouseListener(new MouseAdapter() { int animDuration = 400; long startTime; Timer timer = new Timer(30, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { long currentTime = System.nanoTime() / 1000000; long totalTime = currentTime - startTime; if (totalTime > animDuration) { startTime = currentTime; timer.stop(); return; } // interpolate float fraction = (float) totalTime / animDuration; if (frameParent != null) { float newOpacity = frameParent.getOpacity(); if (focusWindow) { newOpacity += fraction; } else { newOpacity -= fraction; } if (newOpacity > 1f) { newOpacity = 1f; timer.stop(); } else if (newOpacity < EXIT_WINDOW_OPACITY) { newOpacity = EXIT_WINDOW_OPACITY; timer.stop(); } frameParent.setOpacity(newOpacity); } repaint(); } }); @Override public void mouseEntered(MouseEvent e) { focusWindow = true; startTime = System.nanoTime() / 1000000; timer.start(); } @Override public void mouseExited(MouseEvent e) { focusWindow = false; startTime = System.nanoTime() / 1000000; timer.start(); } }); } public static void main(String[] args) { JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main Main = new Main(); frame.add(Main); Main.apply(frame); frame.setSize(300, 210); frame.setVisible(true); } }