Create translucent windows in Java Swing

Java Programming Java8Object Oriented Programming

With JDK 7, we can create a translucent window using swing very easily. With following code, a JFrame can be made translucent.

// Set the window to 55% opaque (45% translucent).
frame.setOpacity(0.55f);

Example

See the example below of a window with 55% translucency.

import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Tester {
   public static void main(String[] args)  {              
      JFrame.setDefaultLookAndFeelDecorated(true);
         // Create the GUI on the event-dispatching thread
         SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            createWindow();                
         }
      });
   }

   private static void createWindow() {          
      JFrame frame = new JFrame("Translucent Window");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.setLayout(new GridBagLayout());
      frame.setSize(200, 200);            
      frame.setLocationRelativeTo(null);      
       
      //Add a sample button.
      frame.add(new JButton("Hello World"));

      // Set the window to 55% opaque (45% translucent).
      frame.setOpacity(0.55f);
      frame.setVisible(true);          
   }  
}

Output

raja
Published on 25-Jul-2018 14:45:59
Advertisements