setIcon根本不显示图像

问题描述 投票:0回答:1

我已经在线尝试了许多解决方案,但似乎没有任何效果。我正在尝试为我的国旗猜谜游戏显示国旗。我在JLabel函数中为flagIconJLabel displayFlag()设置了图标,但是当我运行程序时,它实际上并未显示标志图像。我没有看到任何错误,因此被卡住了。路径很好,我可以自己显示图像。

  private void displayFlag(){
    currentIndex = getUniqueRandomNumber();
    String country =
        (String) selectCountryJComboBox.getItemAt(currentIndex);
    String countryPath = "images/" + country + ".png";
    flagIconJLabel.setIcon(new ImageIcon(countryPath));}

  public static void main(String[] args){
    FlagQuiz application = new FlagQuiz();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
java swing jframe jbutton embedded-resource
1个回答
1
投票

尝试一下,它对我有用,虽然我在同一包中有图像,但是您也可以发送相对路径,我正在使用imageicon的其他构造函数,其中传递URL我尝试将图像路径作为字符串传递对我不起作用

   protected static ImageIcon createImage(String path, String description) {
        URL imageURL = YourClass.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.