Wednesday, November 7, 2012

How to apply a shape into a JFrame

Hello there People! I'm back after a long time. And what I'm gonna give you today, is a little programming trick. Today I'm gonna tell you a trick you can do to a JFrame with the com.sun.awt.AWTUtilities Class. It is how to apply a shape into your JFrame. This is also quite simple as the previous one. All we have to do is, creating a Shape object using Java 2D and then apply it into your JFrame. For this description I will use an Ellipse2D object and apply it into a JFrame you can also create any shape in Java 2D as you want, like Rectangle2D or RoundedRectangle2D. So for this example I create our Ellipse2D object like this,

Shape myShape = new Ellipse2D.Float(0, 0, this.getWidth(), this.getHeight());

For those 4 argument values, you have to give the following
1 - The X coordinate of your Shape object
2 - The Y coordinate of your Shape object
3 - The width which to set for your Shape object
4 - The height which to set for your Shape object

(For the 3rd and 4th arguments I have given the width and height of the JFrame. You can use any value you want for them.)

Like in RoundedRactangle2D objects you will have some 5th and 6th arguments too to give as the width of the arc and the height of the arc of the RoundedRectangle2D. That is to decide how round the corners of your JFrame should be. However now we will proceed with the rest our task.

Now the only thing we have to do is to apply the our Shape object to the JFrame. to do this we will use the setWindowShape() method in AWTUtilities Class. This method also have some two arguments to pass into. for the first one you have to give the JFrame which you want to apply your created Shape and for the second one give the Shape object which you want to apply into your JFrame. So here's how the code will look like

AWTUtilities.setWindowShape(this, myShape);

I have given the JFrame as this because I'm applying the shape into the same JFrame which I'm working. And you see that I have given the SHape object we created into the second argument.

So that's it. Applying a shape into your JFrame is done. :) This is how the complete code will look like,

Shape myShape = new Ellipse2D.Float(0, 0, this.getWidth(), this.getHeight());
AWTUtilities.setWindowShape(this, myShape);

Try it. You can also create some cool JFrame by applying a Shape like this. If you have any problem, just comment here and I'll answer it. I'm always here for you all. Have a nice day ahead guys n gals!! :)




No comments:

Post a Comment