0
我正在尋找在JPanel上顯示圖像,但是當我運行代碼時,面板是空白的。我正在嘗試的方法是this tutorial的稍微修改版本。將JLabel添加到JPanel的問題
我已確認代碼中的所有方法實際上都是使用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));
}
}
這是你的文件,它是壞的:'文件路徑=「FILEPATH_OMITTED」;'?不是像'path/image.png'這樣的想法嗎? – pzaenger
在使框架可見之前,將面板添加到框架**。不要爲您的JPanel使用空佈局。 –
大概路徑是錯誤的,但是我們不知道,因爲你省略了:) – Frakcool