我一直在尝试通过此类实现 JPanel 来打开图像。为什么我的代码不显示图像?它编译、运行、打开 Java,然后关闭它。
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
public class ImagePanel extends JPanel{
private ImageIcon coin;
public ImagePanel(){
ImageIcon coin = new ImageIcon("coin.gif");
}
public void paintComponent(Graphics g){
int x = 5;
int y = 10;
if(coin != null)
coin.paintIcon(this, g, x, y);
}
public static void main(String[] args){
ImagePanel window = new ImagePanel();
window.setBounds(100, 100, 395, 355);
window.setVisible(true);
}
}
最佳答案
您的类扩展了 JPanel
,它是一个 JComponent
。
为了显示您的 JComponent
,您需要将其附加到 JFrame
。
您应该将 main
更改为
public static void main(String[] args)
{
ImagePanel window = new ImagePanel();
JFrame frame = new JFrame();
frame.setBounds(100, 100, 395, 355);
frame.setContentPane(window);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
关于java - 通过 JPanel 获取 .gif 显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49046801/