我尝试将ImageIcon放入Java时出错

时间:2016-11-22 10:11:10

标签: java swing icons label

我尝试在使用BoxLayout格式化的JPanel中放置一个简单的图标。

    JPanel panel_4 = new JPanel();
    contentPane.add(panel_4, BorderLayout.CENTER);
    panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.X_AXIS));

    ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");

    JLabel lblNewLabel_1 = new JLabel(seven);
    panel_4.add(lblNewLabel_1);

当我运行代码时,它给了我错误“Some characters cannot be mapped using "Cp1252" character encoding”,我保存了UTF-8,现在它启动但我看不到图标。

2 个答案:

答案 0 :(得分:1)

也许如果你使用setIcon会帮助你:

ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel();
//Set your icon to your label
lblNewLabel_1.setIcon(seven);
panel_4.add(lblNewLabel_1);

您可以阅读有关图标here

的更多信息

答案 1 :(得分:0)

你需要一个输入流来读取图片。像这样使用它:

File f = new File("filepath");
        InputStream in=new FileInputStream(f);
            if (in != null) {
                ImageIcon imageIcon = new ImageIcon(ImageIO.read(in));
                label.setIcon(imageIcon);
            } else {
                LOG.debug("No icon found...");
            }