Java JFrame create transparent window

Introduction

The alpha value refers to the level of transparency:

Value Meaning
PERPIXEL_TRANSLUCENTRepresents the system support for some of the pixels to be set with potentially different alpha values
PERPIXEL_TRANSPARENT Represents the system support for all of the pixels to be set to either 0.0f or 1.0f
TRANSLUCENT Represents the system support for all of the pixels to be set with an alpha value

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main extends JFrame {
  private JButton closeButton = new JButton("Close");

  public Main(String title) {
    super(title);
    initFrame();/*  w  w w. j  a  v  a 2  s .  c  om*/
  }

  public void initFrame() {
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Make sure the frame is undecorated
    this.setUndecorated(true);

    // Set 40% opacity. That is, 60% translucency.
    this.setOpacity(0.40f);

    // Set its size
    this.setSize(200, 200);

    // Center it on the screen
    this.setLocationRelativeTo(null);

    // Add a button to close the window
    this.add(closeButton, BorderLayout.SOUTH);

    // Exit the application when the close button is clicked
    closeButton.addActionListener(e -> System.exit(0));
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      Main frame = new Main("Translucent Frame");
      frame.setVisible(true);
    });
  }
}



PreviousNext

Related