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

    Default JButton : Background and Text

    Hello,

    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 offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    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 {
    
      @Override
      public int getIconWidth() {
        return 0;
      }
    
      @Override
      public int getIconHeight() {
        return 0;
      }
    
      @Override
      public void paintIcon(Component c, Graphics g, int x, int y) {
        g.setColor(Color.ORANGE);
        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.

    db

Similar Threads

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