Create shaped windows in Java Swing


With JDK 7, we can create a shaped window using swing very easily. Following are the steps needed to make a shaped window.

 Add a component listener to frame and override the componentResized() to change the shape of the frame. This method recalculates the shape of the frame correctly whenever the window size is changed.

frame.addComponentListener(new ComponentAdapter() {
   @Override
   public void componentResized(ComponentEvent e) {
      frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),
      frame.getHeight(), 20, 20));
   }
});

Example

See the example below of a shaped window.

import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;

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("Rounded Shaped Window");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setVisible(true);          
   }

   private static void createUI(final JFrame frame) {
      frame.setLayout(new GridBagLayout());
      frame.setSize(200, 200);            
      frame.setLocationRelativeTo(null);              
      frame.add(new JButton("Hello World"));  

      frame.addComponentListener(new ComponentAdapter() {
         @Override
         public void componentResized(ComponentEvent e) {
            frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),
               frame.getHeight(), 20, 20));
         }
      });
   }
}

Output

Updated on: 19-Jun-2020

692 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements