gpt4 book ai didi

java - 将 JLabel 添加到 JPanel 时出现问题

转载 作者:行者123 更新时间:2023-12-02 03:59:09 25 4
gpt4 key购买 nike

我希望在 JPanel 上显示图像,但是当我运行代码时,面板是空白的。我正在尝试的方法是 this tutorial 的稍微修改版本。 .

我已经确认代码中的所有方法实际上都是使用 println 调用的。我的框架和面板是可见的,并且我相当确定我已将图标添加到标签,并将标签添加到面板。我错过了什么?

我的代码的相关部分:

public class SYSTEM
public static void start() {
GameFrame GF = new GameFrame();
GamePanel GP = new GamePanel();
GF.add(GP);
GP.loadSprite("Player", new Dimension(0,0));
}
}

public class GameFrame extends JFrame {
public GameFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(SYSTEM.windowSize);
setVisible(true);
}
}

public class GamePanel extends JPanel {
ArrayList<Sprite> sprites = new ArrayList<Sprite>();
GamePanel() {
setVisible(true);
setSize(SYSTEM.windowSize);
setLayout(null);
}
public void loadSprite(String spriteName, Dimension pos) {
sprites.add(new Player());
add(sprites.get(0).getIcon());
}

public class Sprite {
protected JLabel icon;
protected BufferedImage image;
protected String filePath;
protected Dimension pos;
public JLabel getIcon() {
return icon;
}
}

public class Player extends Sprite {
public Player() {
filePath = "FILEPATH_OMITTED";
pos = new Dimension(0,0);
try {
image = ImageIO.read(new File(filePath));
} catch (IOException e) {
System.out.println(e);
}
icon = new JLabel(new ImageIcon(image));
}
}

最佳答案

不要在游戏中使用组件,你已经抛弃了负责确定组件大小和位置的布局管理器,但你却未能弥补它。我建议您改用自定义绘画方法,请参阅 Painting in AWT and SwingPerforming Custom Painting首先。

我很清楚,您的问题与 setLayout(null); 直接相关,无论您在做什么,这都是不好的

关于java - 将 JLabel 添加到 JPanel 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093290/

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