2

我正在尝试在 Jform 的面板中制作图像按钮数组。为此,我想通过提供路径来添加图像,但这里是无法读取输入文件的 IO 异常。错误发生为

Exception in thread "main" javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at serverui.ImageArray.main(ImageArray.java:38)

代码如下: package serverui;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageArray {
    Image[] images;

    public ImageArray(Image[] images) {
        this.images = images;
    }

    private JPanel getContent() {
        JPanel panel = new JPanel(new GridLayout(0,2,5,5));
        panel.setBackground(Color.green.darker());
        for(int i = 0; i < images.length; i++) {
            ImageIcon icon = new ImageIcon(images[i]);
            JLabel label = new JLabel(icon, JLabel.CENTER);
            panel.add(label);
        }
        return panel;
    }

    public static void main(String[] args) throws IOException {

        String prefix = "images/";
        String[] ids = { "desktopactive", "desktopoff" };
        String ext = ".png";
        Image[] images = new Image[ids.length];
        for(int i = 0; i < images.length; i++) {
            String path = prefix + ids[i] + ext;
            images[i] = ImageIO.read(new File(path));
        }

        ImageArray app = new ImageArray(images);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(app.getContent());
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
    }
}
4

3 回答 3

1

如下更改您的代码,路径中的问题

   String prefix = "D:\\TestFolder\\";
    String[] ids = { "Capture"};
    String ext = ".png";
    Image[] images = new Image[ids.length];
    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        images[i] = ImageIO.read(new File(path));
    }

通过这种方式,它对我有用。有时,如果您在驱动器(操作系统安装分区)中提供prefixas 文件夹,您可能由于权限问题而无法读取该文件。C上面的其他内容将解决您的问题。

于 2013-08-15T07:10:13.313 回答
0

您应该确保这两个文件都存在。

    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        File file = new File(path);
        if (!file.exists()) {
            throw new IllegalArgumentException("file "+file+" does not exist");
        }
        images[i] = ImageIO.read(file);
    }

确保它images与您当前的目录相关。如果你把images你的类路径,你可以使用这个:

    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        URL url = ImageArray.class.getResource(path);
        if (url == null) {
            throw new IllegalArgumentException("url "+url+" does not exist");
        }
        images[i] = ImageIO.read(url);
    }
于 2013-08-15T07:10:39.733 回答
0

好吧,这取决于您的平台,如果这确实在 Windows 上。那么您需要将其更改为 \ on

String prefix = "images/"

但是,如果您愿意,您可以做的是创建一个 if 语句,该语句根据操作系统修改字符串。你得到你所拥有的操作系​​统的方式是通过

System.getProperty("os.name")
于 2013-08-15T07:11:45.710 回答