Creating a varying gradient translucent window - Java Swing

Java examples for Swing:JFrame

Description

Creating a varying gradient translucent window

Demo Code

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GraphicsDevice;
import java.awt.GraphicsDevice.WindowTranslucency;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main extends JFrame {

    public Main() {
        this.setTitle("Gradient Translucent Window");
        setBackground(new Color(0, 0, 0, 0));
        this.setSize(200, 200);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {

            @Override/*from www .  j  a va  2s.c  o  m*/
            protected void paintComponent(Graphics gradient) {
                if (gradient instanceof Graphics2D) {
                    final int Red = 120;
                    final int Green = 50;
                    final int Blue = 150;
                    Paint paint = new GradientPaint(0.0f, 0.0f,
                            new Color(Red, Green, Blue, 0),
                            getWidth(), getHeight(),
                            new Color(Red, Green, Blue, 255));
                    Graphics2D gradient2d = (Graphics2D) gradient;
                    gradient2d.setPaint(paint);
                    gradient2d.fillRect(0, 0, getWidth(), getHeight());
                }
            }
        };
        this.setContentPane(panel);
        this.setLayout(new FlowLayout());

        JButton exitButton = new JButton("Exit");
        this.add(exitButton);
        exitButton.addActionListener(e->System.exit(0));

    }
    public static void main(String[] args) {               
      GraphicsEnvironment envmt = 
            GraphicsEnvironment.getLocalGraphicsEnvironment();
      GraphicsDevice device = envmt.getDefaultScreenDevice();
        
        if (!device.isWindowTranslucencySupported(WindowTranslucency.PERPIXEL_TRANSLUCENT)) {
           System.out.println("Translucent windows are not supported on your system.");
           System.exit(0);
        }
        JFrame.setDefaultLookAndFeelDecorated(true);
        SwingUtilities.invokeLater(()->{
                Main window = new Main();
                window.setVisible(true);
        });

    }
}

Related Tutorials