Java JFrame don'中的图像;t显示

Java JFrame don'中的图像;t显示,java,image,swing,Java,Image,Swing,我正在尝试将图像添加到我的程序中,其中两个图像有问题。Ball.png和ground.png不显示 我在哪里犯了错误 当我添加球和地面的图像作为背景时,没有问题 public class Game extends JPanel implements ActionListener { Image ball; Image ground; Image arrow; public Game(){ try { ball = ImageIO.read(new File("

我正在尝试将图像添加到我的程序中,其中两个图像有问题。Ball.png和ground.png不显示

我在哪里犯了错误

当我添加球和地面的图像作为背景时,没有问题

    public class Game extends JPanel implements ActionListener {

Image ball;
Image ground;
Image arrow;

public Game(){
    try {
        ball = ImageIO.read(new File("ball.png"));
    } catch (IOException e) { 
        System.out.println("pliku brak");
    }
    try {
        ground = ImageIO.read(new File("ground.png"));
    } catch (IOException ex) {
        System.out.println("pliku brak");
    } 
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(ball, 100, 100, null);
    g.drawImage(ground, 300, 300, null);
}
@Override
public void actionPerformed(ActionEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}


public class Start {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            okienko();
        }
    });
}

public static void okienko()
{    

    JFrame frame = new JFrame("Hold The Ball");

    try
    {
        frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("background.png")))));
    } catch (IOException e)
        {
            System.out.println("pliku brak");
        }
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Game());
    frame.setSize(1000, 600);
    frame.setResizable(false);
    frame.setVisible(true);       
}
}

您应该使用带有ImageIcon的图像路径,然后将图标设置为JLabel

ImageIcon=newImageIcon(“images/background.png”); JLabel标签=新的JLabel(图标)

您可以阅读以下内容:
您无法看到您的
游戏JPanel
,因为您的
JFrame
中填充了
frame.setContentPane(…)
Background
JLabel
。您需要使用
LayoutManager
将面板放置在另一个面板上

 frame.setLayout(new BorderLayout());
 frame.add(new Game(), BorderLayout.CENTER);
将解决此问题。
但是你将看不到背景,因为你的
游戏JPanel
是最重要的。若要修复此问题,应使此面板具有不可见的背景。
所以加上


到你的
游戏
构造器。

不要尝试这样分层组件

这里最好的方法是在绘制其他游戏元素的同时绘制背景。为此:

  • 改变

    Image arrow; 
    

  • 与其他两个映像同时加载BG
  • paintComponent(Graphics)
    方法中首先绘制背景(0x0)

  • 使用
    ImageIO
    加载图像是更好的方法,因为它会在失败时提供反馈。1)
    g.drawImage(ball,100,100,null)应该是
    g.drawImage(ball,100100,this)2)帧设置大小(1000600)替代
    游戏
    面板的首选大小方法,以返回比赛场地/游戏大小。然后,在添加帧后,将其装入
    pack()
    。这将是准确的正确大小。
    Image arrow; 
    
    Image arrow; 
    Image bg; // declare the BG as a class attribute of the Game class