通过JPanel显示.gif?

问题描述 投票:0回答:1

我一直试图通过这个实现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);
}
}
java image jpanel display
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.