我一直试图通过这个实现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);
}
}
答案 0 :(得分:1)
您的课程扩展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);
}