Saturday, June 8, 2013
Today I will tell you how you can create shaped windows in Java. This is an extraordinary feature which was added in Java7. According to this feature you can create any shape and use that shape for your window. You can also create complex shapes and give your windows that shape. Different shapes like oval, round rectangle or complex like L-shape or I-shape. Here we will inherit the JFrame class and then add the ComponentListener to it. This is because when the window will be resized the shape will be calculated automatically. We will create a shape using Ellipse2D.Double and then call setShape() method to assign the shape to it. Below is a screenshot
An oval-shaped window as seen on Ubuntu 12.04
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;

public class OvalShapedWindow extends JFrame {
    public OvalShapedWindow() {
        super("Oval Window");
        setLayout(new GridBagLayout());  //setting layout

        addComponentListener(new ComponentAdapter() {
          // If the window is resized, the shape is recalculated
          @Override
          public void componentResized(ComponentEvent e) {
            Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
            setShape(winShape);  //giving shape
          }
        });

        setUndecorated(true);  //removing title-bar
        setSize(350,250);
        setLocationRelativeTo(null);  //positioning at center
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JButton("Click Me"));  //adding Button
    }

     public static void main(String[] args) {
        // Creating UI on the event-dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            OvalShapedWindow sw = new OvalShapedWindow();
            sw.setVisible(true);  // Display the window
          }
        });
    }
}

--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters