How to set text on jButton

653 views Asked by At

So I am currently working on generating on small program, that takes for instance car parts, points to one of them and then gives you 3 options and you have to choose the correct one. I decided to customize the JButton's with options, because I didn't like the shapes and colors. So I made the rectangles 3D and applied the image as a background.

And this is where my trouble started: after applying the background, I can't use setText, because the text doesn't appear on the button. I was thinking whether I should try to come up with own setText, but I have no clue, where to start. Can you guys give me any pointers on where to start or how to fix it?

THis is my code so far:

public class Button extends JButton { private String link;

public Button(String link) {
    this.link = link;

}
public void setBackground(){ // sets the background to a particular image on the drive
    try {
        Image img = ImageIO.read(new File(this.link));
        paintComponent(img.getGraphics());
        setTest("Siema");
    } catch (IOException e) {
        System.out.println("Doesn't exist");
    }
}

public void setTest(String string) { // PROBLEM!
    this.setText(string);

}
public void paintComponent(Graphics g) /overrides the paintComponent method to draw the image
{
Image img;
try {
    img = ImageIO.read(new File(this.link));
    g.drawImage(img, 0, 0, null);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

} }

I think the picture is generated over the button and therefore I can't see the text.

1

There are 1 answers

5
Nookie_IN On BEST ANSWER

I think SetText isn't working because you'r painting over it with setBackground.