Results 1 to 2 of 2
  1. #1
    Keys is offline Member
    Join Date
    May 2011
    Rep Power

    Default JButton : Background and Text


    I want to create a JButton with an image in background and a dynamic text.

    I create my own derived JButton to implement paintComponent() method.
    So my background is ok but when I try to use setText() I can't see my text...

    Then I try to implement drawString() method in my button. With this method I can see my text but my background disappear !

    Please can you tell me how to fix that and create button with background and text ?

    Thank you.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is online now Forum Police
    Join Date
    Sep 2008
    Madgaon, Goa, India
    Rep Power


    There's no need to reinvent the wheel. JButton has setIcon and setText methods (also setRolloverIcon / setPressedIcon / serDisabledIcon ... did I miss any?

    You can create an implementation of Icon that returns 0 for its width and height (thus ensuring that the button doesn't reserve space for the Icon) and paints the entire background (using getWidth() / getHeight() of the Component parameter to paintIcon. Something like (mayhave typos)
    Java Code:
    class BackgrouindIcon implements Icon {
      public int getIconWidth() {
        return 0;
      public int getIconHeight() {
        return 0;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillRect(0, 0, c.getWidth(), c.getHeight());
    This may displace the button's text off-center due to the text-icon gap. You can fine-tune this either by setIconTextGap(0) or by setting the horizontal and vertical text position to CENTER.


Similar Threads

  1. Adding JButton to JFrame with background
    By bzknight in forum AWT / Swing
    Replies: 1
    Last Post: 01-19-2011, 06:55 PM
  2. Replies: 13
    Last Post: 09-29-2010, 10:55 PM
  3. PDFBOX change text colours and remove background
    By gstkein in forum Advanced Java
    Replies: 1
    Last Post: 11-20-2009, 11:54 AM
  4. Replies: 4
    Last Post: 03-21-2009, 05:48 PM
  5. JButton onClick change color background
    By behrk2 in forum AWT / Swing
    Replies: 6
    Last Post: 07-09-2008, 04:54 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts