Tuesday, July 31, 2012

Custom Shape Buttons

Buttons of Irregular Shape

In previous post, I have demonstrated how to detect mouse click in a triangular region. That made implementation of a triangular button possible. In this post I will move one step forward. I am going to implement a button with arbitrary shape.

Transparent Image

First you will need a transparent image file to act as the button. It is not difficult to make one yourself. I have prepared one for you:

Download it and save it as "a.png". Place it at the same folder as ImageButton.java.


The actual code is simple, we will simulate a button using a JLabel. We will attach a image to the JLabel, then capture the mouse event, and ignore the mouse click if it click on a transparent pixel.


  1. Nice post! i have tried your code and its worked pretty well. but now that i am using my own image file it doesn't seem to work. Im using image from this web page:http://www.fabiovisentin.com/24_5/transparent-isolated-flowers-rose.ashx. any help is appreciated...

    1. There is a bug.
      The original version was:
      boolean transparent = (image.getRGB(e.getX(),e.getY()) & 0x00ffffff)!=0;
      This is wrong. The correct version should be:
      boolean transparent = (image.getRGB(e.getX(),e.getY()) & 0xFF000000)==0;
      I have updated the source above and you may copy ImageButton.java again.