簡體   English   中英

JLabel 不會在 class 中顯示圖像

[英]JLabel won't display image in class

我目前正在嘗試創建一個 GUI,其中兩個硬幣圖像在邊框布局的中心彼此相鄰顯示。 我有一個 class(圖像),我嘗試使用 JLabel 顯示圖標和另一個處理 GUI 框架(GameGUI)的 class。 然而,盡管我盡了最大的努力,標簽並沒有顯示圖像。 我瀏覽了無數教程,找不到任何可以解決此問題的方法。 相對路徑是正確的,我該如何解決?

圖像 Class

public class Images extends JLabel{

    private JLabel heads, tails;

    public Images() {
        heads = new JLabel(new ImageIcon("img/heads.png"));
        tails = new JLabel(new ImageIcon("img/tails.png"));
        add(heads);
        add(tails);
    }
}

游戲GUI Class

public class GameGUI extends JFrame{

    public GameGUI() {
        super("");
        setLayout(new BorderLayout(10,10));

        Menu menu = new Menu();
        ToolBar toolBar = new ToolBar();
        Images images = new Images();

        setJMenuBar(menu);

        add(BorderLayout.NORTH, toolBar);
        add(BorderLayout.CENTER, images);

        setSize(1000, 500);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

問題:

public class Images extends JLabel{

    private JLabel heads, tails;

    public Images() {
        heads = new JLabel(new ImageIcon("img/heads.png"));
        tails = new JLabel(new ImageIcon("img/tails.png"));
        add(heads);
        add(tails);
    }
}

JLabel 使用 null 布局,這意味着您的內部 JLabel 組件的大小將為 0、0,並且圖像 JLabel 本身將具有相同的首選大小,並且不會顯示任何內容,因此您永遠不想將 JLabel 添加到J標簽。 不要讓圖像擴展 JLabel,而是 JPanel,並給它一個像樣的布局,也許是 GridLayout。

例如,

public class ImagePanel extends JPanel {
    private JLabel headsLabel = new JLabel();
    private JLabel tailsLabel = new JLabel();

    public ImagePanel(Icon headsIcon, Icon tailsIcon) {
        headsLabel.setIcon(headsIcon);
        tailsLabel.setIcon(tailsIcon);
        setLayout(new GridLayout(1, 0);
        add(headsLabel);
        add(tailsLabel);
    }       
}

同樣,我建議將圖像作為資源獲取,而不是使用 ImageIO 讀取的文件,例如

Image headImage = ImageIO.read(getClass().getResource(resourcePath));
Icon headIcon = new ImageIcon(headImage);

資源路徑很重要,取決於圖像相對於 class 文件的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM