如何在 jButton 上设置文本

How to set text on jButton

所以我目前正致力于生成小程序,例如获取汽车零件,指向其中之一,然后给你 3 个选项,你必须选择正确的一个。 我决定使用选项自定义 JButton,因为我不喜欢它的形状和颜色。所以我制作了矩形 3D 并将图像应用为背景。

这就是我的麻烦开始的地方:应用背景后,我无法使用 setText,因为文本没有出现在按钮上。我在想我是否应该尝试提出自己的 setText,但我不知道从哪里开始。你们能给我一些关于从哪里开始或如何修复它的指示吗?

到目前为止,这是我的代码:

public class 按钮扩展了 JButton { 私有字符串 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();
}

} }

我认为图片是通过按钮生成的,因此我看不到文字。

我认为 SetText 不起作用,因为您正在使用 setBackground 对其进行绘制。