Figure 1.1 My simple window
I like Flash buttons because you can easily change the attributes of the buttons depending on the situation, such as mouse over or mouse click. You can do this easily in Java.
Many people load different graphics using these methods in
setPressedIcon(icon). To me, it works, but is not too efficient. I will show you how to process the image during runtime by using Java
Java Swing is a technology for desktop. If used properly, it can hardware-accelerate the image you upload. I won’t cover hardware-accelerated images here, because I think you can Google about it.
Figure 2.1 The State
As you can see, the initial state of the button is a little bit transparent. When you put your mouse over it, the image will become more visible. When clicked, the image will move by x=1px and y=1px.
Using the code
The class that is included with this article is named
The most important method in the
MouseOverButton class is
JButton createButton(String pathName, String toolTip) and
BufferedImage createCompatibleImage(int w, int h, int transparancy).
createCompatibleImage(w,h, transparency) returns a
BufferedImage that supports the specified transparency, and has a data layout and color model compatible with this
public BufferedImage createCompatibleImage(int w, int h, int transparancy)
GraphicsConfiguration gc = getGraphicsConfiguration();
return gc.createCompatibleImage(w, h, transparancy);
We will make three images. The first image is the image that we load. This image is used when the mouse cursor is over the image.
The second image makes the translucent default image. This is the image in the initial state.
Image image = createCompatibleImage(w, h, Transparency.TRANSLUCENT);
Graphics2D g = (Graphics2D)image.getGraphics();
Composite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f);
g.drawImage(imageRollover.getImage(), 0,0, null);
ImageIcon iconDefault = new ImageIcon(image);
We set the alpha to be 0.5, that is 50% of the total image visibility (if alpha=1.0f, the image is fully visible). Then, set the composite for the image before drawing it on the screen.
The third image is fully visible. We will draw the image by setting x=1 and y=1 (offset the image by a few pixels) so that it will give the effect that the button has been pressed.
image = createCompatibleImage(w, h, Transparency.TRANSLUCENT);
g = (Graphics2D)image.getGraphics();
ImageIcon iconPressed = new ImageIcon(image);
I think that is all that I can tell you about my program. The rest is self-explanatory, or you can read about it in the Java documentation because it is all simple. If you have any enquiries or thinks that I need to elaborate more, don’t hesitate to contact me.
You can be more creative; you can use it to make your program more interactive and look cool.
The image I used for this tutorial is downloaded from CodeProject itself.
Brackeen, D. (2004). Developing Games in Java. New Riders Publishing.