如何设置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的内容窗格,但我不知道如何为JButton执行此操作
答案 0 :(得分:2)
在JButton上显示图像的最佳方法是使用按钮创建ImageIcon,然后通过setIcon(myIcon)
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();
}
}
你说:
这不会将其设置为背景。它只是在文本旁边创建一个图标
然后你有几个选择: