0

I am setting background image for JButton or say JTableHeader. When I do paintComponent on the same, it's removing text value set for that component.

Any idea where I am going wrong?

JButton btn = new JButton(){
    @Override
    public void paintComponent(Graphics g){
        Dimension size = this.getSize();
        g.drawImage(Toolkit.getDefaultToolkit().getImage("C:\\User\\Downloads\\MainMenu.jpg"), 0, 0, size.width, size.height, this);
    }
};
btn.setText("TEST WITH ME");
btn.setOpaque(true);

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Rohit Borse
  • 75
  • 1
  • 10
  • 2
    1) In any overridden paint method, always call the `super` method first. This paints the background, borders etc. 2) `g.drawImage(Toolkit.getDefaultToolkit().getImage("C:\\User\\..` Don't load resources within a paint method. A paint method has to finish quickly! Load the image at application startup and store it as an attribute of the class. 3) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 4) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Nov 26 '17 at 11:26
  • 2
    .. `btn.setText("TEST WITH ME");` 5) The text can be passed in the button constructor. 6) No need to SHOUT at the user. Better to use `"Test With Me"` or `"Test with me"` – Andrew Thompson Nov 26 '17 at 11:32
  • Possible duplicate of [How to create a custom JButton in java with an image base?](https://stackoverflow.com/questions/8235991/how-to-create-a-custom-jbutton-in-java-with-an-image-base) – user1803551 Nov 26 '17 at 12:37
  • You've basically broken the paint chain requirements – MadProgrammer Nov 26 '17 at 21:20

2 Answers2

0

I am setting background image for JButton

The is no need to do custom painting. You just add an Icon to the button and the button will paint the image.

If you want text on top of the image then you just use the properties of the button:

button.setHorizontalTextPosition(...);
button.setVerticalTextPosition(...);
camickr
  • 321,443
  • 19
  • 166
  • 288
0

I may have not specified that much correct what I really wanted. But I figured out answer for that.

@Override
public void paintComponent(Graphics g){
    Dimension size = this.getSize();
    g.drawImage(Toolkit.getDefaultToolkit().getImage("C:\\User\\Downloads\\MainMenu.jpg"), 0, 0, size.width, size.height, this);
    FontMetrics fm = g.getFontMetrics();
    int x = (getWidth() - fm.stringWidth("String Value To Set")) / 2;
    int y = ( (getHeight() - fm.getHeight() ) / 2) + fm.getAscent() ;
    g.drawString(String Value To Set, x, y);
}
Rohit Borse
  • 75
  • 1
  • 10