我正在尝试在 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);
}
}