我正在尝试创建一个Java桌面应用程序,其中我有一个JLabel
我在其中随机播放图像。我正在从我的电脑的任何驱动器上的文件夹中检索图像。现在我想从图像文件夹名称可用的项目文件夹中检索所有图像。
F:/>Kiosk
|
|___src
|
|___lib
|
|___koisk
|
|__main1.java
|
|__images
这是我的代码 我怎样才能做到这一点?
public class ImageShuffle1 extends JPanel {
private List<BufferedImage> list = new ArrayList<BufferedImage>();
private List<BufferedImage> shuffled;
private JLabel label = new JLabel();
private int width = 700;
private int height = 700;
private Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
update();
}
});
public ImageShuffle1() {
try {
list.add(resizeImage(ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.jpg"))));
list.add(resizeImage(ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg"))));
list.add(resizeImage(ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg"))));
list.add(resizeImage(ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\f.jpg"))));
} catch (IOException e) {
e.printStackTrace();
}
shuffled = new ArrayList<BufferedImage>(list);
Collections.shuffle(shuffled);
timer.start();
}
private BufferedImage resizeImage(BufferedImage originalImage) throws IOException {
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private void update() {
if (shuffled.isEmpty()) {
shuffled = new ArrayList<BufferedImage>(list);
Collections.shuffle(shuffled);
}
BufferedImage icon = shuffled.remove(0);
label.setIcon(new ImageIcon(icon));
}
private void display() {
JFrame f = new JFrame("ImageShuffle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.add(label);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ImageShuffle1().display();
}
});
}
}
提前致谢
答案 0 :(得分:4)
将项目中的images
文件夹中的所有图像与src
文件夹并行放置。
F:/>Kiosk
|
|___src
|
|___lib
|
|___koisk
|
|__main1.java
|
|__images
|
|__c.jpg
|__d.jpg
|__e.jpg
|__f.jpg
使用此代码
list.add(resizeImage(ImageIO.read(new File("images\\c.jpg"))));
list.add(resizeImage(ImageIO.read(new File("images\\d.jpg"))));
list.add(resizeImage(ImageIO.read(new File("images\\e.jpg"))));
list.add(resizeImage(ImageIO.read(new File("images\\f.jpg"))));
- 编辑 -
你可以尝试任何一个
// Read from same package
list.add(resizeImage(ImageIO.read(getClass().getResourceAsStream("c.png"))));
// Read from absolute path
list.add(resizeImage(ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"))));
// Read from images folder parallel to src in your project
list.add(resizeImage(ImageIO.read(new File("images\\c.jpg"))));
对所有四张图片重复任何一张。