我有一个ImageBean类,我想用它来加载数组中的图像。我已经使用图像预加载了数组(总共9个),并且每次刷新浏览器时都想连续显示一个图像。图像命名为“1.jpg,2.jpg”等 (即图像'1' - 刷新,图像'2'点击刷新,...图像'9')。任何帮助将不胜感激。感谢。
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import javax.imageio.ImageIO;
@ManagedBean(name="ImageBean")
@SessionScoped
public class ImageBean implements Serializable
{
private static final long serialVersionUID = 1L;
ArrayList<Image> myArr = new ArrayList<Image>();
BufferedImage img = null;
public ImageBean()
{
for(int i = 1; i < 10; i++)
{
try
{
img = ImageIO.read(new File(i + ".jpg"));
}
catch (IOException ex) {}
myArr.add(img);
}
}
public BufferedImage getImage(int i)
{
return (BufferedImage) myArr.get(i);
}
}
编辑1
我已稍微编辑了代码,因此我使用BufferedImage数组而不是ArrayList。现在我没有收到错误,但图片没有显示在浏览器中。
public class ImageBean implements Serializable
{
private static final long serialVersionUID = 1L;
BufferedImage[] myArr = new BufferedImage[9];
public ImageBean()
{
for(int i = 0; i < 9; i++)
{
try
{
myArr[i] = (ImageIO.read(new File(i+1 + ".jpg")));
}
catch (IOException ex) {}
}
}
public BufferedImage getImage(int i)
{
return (BufferedImage) myArr[i];
}
}
答案 0 :(得分:1)
一个简单的解决方案是添加一个变量来保存当前图像并获取下一个图像...(请记住重置最后一个图像)
@SessionScoped
public class ImageBean implements Serializable
{
private static final long serialVersionUID = 1L;
ArrayList<Image> myArr = new ArrayList<Image>();
BufferedImage img = null;
private int currImgId = 1;
public ImageBean()
{
for(int i = 1; i < 10; i++)
{
try
{
img = ImageIO.read(new File(i + ".jpg"));
}
catch (IOException ex) {}
myArr.add(img);
}
}
public BufferedImage getImage()
{
// Reset logic would go here...probably best with array.size...
return (BufferedImage) myArr.get(currImgId++);
}
}
答案 1 :(得分:0)
public ImageBean()
{
for(int i = 1; i < 10; i++)
{
try
{
myArr.add(ImageIO.read(new File(i + ".jpg")));
}
catch (IOException ex) {}
}
}
最初如果失败则会继续添加上一张图片。这可能会使它“冻结”,因为它实际上会通过图像,但实际上只是显示相同。