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….
Our software libraries allow you to
Convert PDF to HTML in Java |
Convert PDF Forms to HTML5 in Java |
Convert PDF Documents to an image in Java |
Work with PDF Documents in Java |
Read and Write AVIF, HEIC, WEBP and other image formats |
As I tested your method in my project ( myButton.setIcon(ImageIcon) ) it does NOT set background to JButton. It adds image next to text (on the left to be exact), so it’s not a background. It’s just a picture. To be exact (once again), distance between text and image is set by setTextIconGap(int) method).
So I ask, do You know a way to set background image to JButton instead of standard Java Steel theme?
Which version of Java are you using?
Java SE – fresh download of JDK + NetBeans (writing just in case).
i dont think there is a way to add an image background.
the only option i know is to set the icon, disable the text by setting it to null.
then write a custom imageicon/image or icon,
that draws the background and then draws the text ontop.
extends from jbutton and override the paint method
@Override
public void paint(Graphics g) {
if (bgImage != null) {
g.drawImage(bgImage, 0, 0, getWidth(), getHeight(), this);
setContentAreaFilled(false);
setBorder(null);
} else {
setOpaque(true);
}
super.paint(g);
}