如何设置 JComponent 的背景?我目前有这门课:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JComponent;
public class ImagePanel extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private Image image;
public ImagePanel(Image image) {
this.setLayout(new BorderLayout());
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
private BufferedImage myImage;
private JButton button = new JButton("Click");
try {
myImage = ImageIO.read(new File("/images/picture.png"));
} catch (IOException e) {
e.printStackTrace();
}
我使用以下代码来绘制 JFrame 的内容 Pane ,但我不知道如何为 JButton 执行此操作
最佳答案
在 JButton 上显示图像的最佳方法是使用按钮创建 ImageIcon,然后通过 setIcon(myIcon)
设置 JButton 的图标
private BufferedImage myImage;
private JButton button = new JButton("Click");
public MyClass() {
try {
// much better to get the image as a resource
// NOT as a File
myImage = ImageIO.read(new File("/images/picture.png"));
Icon buttonIcon = new ImageIcon(myImage);
button.setIcon(buttonIcon);
} catch (IOException e) {
e.printStackTrace();
}
}
<小时/>
您声明:
This doesn't set it as background. It just create an icon next to the text
然后你有几个选择:
- 扩展 JButton 并在其 PaintComponent 方法中绘制图像,类似于使用 JComponent 的操作方式。请注意,这会改变按钮边框等的绘制,并且它可能不会像您想要的那样工作,但您可以轻松测试。
- 或者从图像中获取 Graphics 对象,将文本绘制到图像上,然后从中创建一个 ImageIcon 并将其放置在按钮上。
关于JAVA Paint组件的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678598/