gpt4 book ai didi

java - JFrame 中的图像不显示

转载 作者:行者123 更新时间:2023-11-30 03:06:58 29 4
gpt4 key购买 nike

我正在尝试将图像添加到我的程序中,但其中 2 个图像出现问题。 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);
}
}

最佳答案

不要尝试像这样分层组件。

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

  1. 更改

    Image arrow; 

    Image arrow; 
    Image bg; // declare the BG as a class attribute of the Game class
  2. 与其他两个图像同时加载 BG。
  3. 首先在 paintComponent(Graphics) 方法中绘制 BG(在 0x0 处)。

关于java - JFrame 中的图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528529/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com