When i try to add background in Jbutton in java by going to its properties and then icon, it then sets the background of the button but the text which i have written on the button,it moves right(outside the button area).What is the solution for this?
3 Answers
If you wanted to add an Image to your JButton
with NetBeans
follow these steps :
- Right Click
Source Packages
, underProjects
and SelectNew -> Other -> (Under Categories) Select Other -> (Under File Types) Select Folder
. - Click Next, and provide a name to the folder. For Example
resources
, do check that forParent Folder
, src is written inside the field. Now Click Finish. - Now manually go to this location on your Computer and create a New Folder, say images, and then paste the
IMAGE
inside this folder. - Now Under
Design Mode
, select your JButton, and on the Right Side go to thisJButton
's properties. Just under foreground you will seeicon
is written, click the Eclipse Button associated with it to open the window as shown in Figure below : - Do check, this FIGURE 1, to fill in your values and then Press OK
You are done adding image to your JButton.
If you want to use the image I used, here it is .
Yeah, I forgot to mention, for this, I had set horizontalTextPosition = CENTER and veritcalTextPosition = BOTTOM under Other Properties, inside Properties.
And Here is the output of the whole thing :

- 24,468
- 7
- 50
- 143
As far as I understand you are not setting background but you are setting Icon to button by this. And that is why you see Image on right side and text on left side. To add image as background to button you need to override paintComponent(g)
method of JButon
and draw your image in it.

- 58,650
- 30
- 162
- 207
-
-
@Zara I'm not very much familiar with NetBeans. But may be there should some functionality fro writing custom code in jbutton paintComponent method. If you can't find it then create your own class which extends JButton and override paintComponent there. – Harry Joy Mar 06 '12 at 11:28
-
+1, I liked this approach, since I am learning painting now a days in Swing :-) – nIcE cOw Mar 06 '12 at 12:05
What is the solution for this?
One 'solution'1 it to write the text on the image. This is not a very good solution though, since:
- The text would need to be written on each icon used for the button (e.g. normal, roll-over, selected etc.).
- It would then become your responsibility to choose an appropriate font face & size.
- The text would not automatically change font or size when the PLAF changes.
- Things like mnemonics and accelerators will not work with the image-text button.
- It was only when writing the points that it became more clear just how quirky it would be to work with.

- 168,117
- 40
- 217
- 433