Site iconJava PDF Blog

How to set a JButton background

We use a lot of JButtons in our Java PDF viewer and thought that the following observations might be of help to other Java developers.

When you create a JButton it can be transparent (no background) and you can see through them or have a background color. This is done using the method setOpaque(boolean flag) where the flag is true or false. The background color is set using the method – setBackground(Color color)). So a button with a blue background would be

JButton myButton =new JButton(“press me”);

myButton.setBackground(Color.blue);

So far so good but not very exciting in an age when everyone expects lots of eye candy.

Color can be any any value, but you can also define a Color as transparent or semi-transparent. – we use this to mimic Acrobat’s see-through empty signature buttons on a PDF display.

JButton myButton =new JButton(“press me”);

myButton.setBackground(new Color(255,0,0,128));

The four values are R,G,B,A (where A is the transparency or Alpha value so the above example gives a red background which is 50% transparent). If you use integer numbers, they are all between 0 and 255.

There is one more way we could add a fancy background, with an image. This allows you to display a custom image for the Button, which can include transparency and any number of fancy eye candy.

JButton myButton =new JButton(“press me”);
myButton.setIcon(new ImageIcon(image));

In this example image can be an Image or a BufferedImage.

So we have rapidly gone from a dull, boring component to something with huge potential. We can also add some pretty cool ‘rollover’ effects – but that is for another day….