我正在尝试在ArrayList中加载一组图像,但只查看最后一张图片。第一个在面板上看不到。任何信息? 我们的想法是它们按顺序出现在JPanel中。
感谢。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cargaimagenes;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
/**
*
* @author ZOUHIR
*/
public class PanelCarga extends javax.swing.JFrame {
/**
* Creates new form PanelCarga
*/
private List<Image> Imagenes = new ArrayList<Image>();
private JLabel eq = new JLabel();
private Image imagen = new Image() {
@Override
public int getWidth(ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getHeight(ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ImageProducer getSource() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Graphics getGraphics() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getProperty(String name, ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
public PanelCarga() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
PanelP = new javax.swing.JPanel();
lPrincipal = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jToggleButton1 = new javax.swing.JToggleButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
PanelP.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
javax.swing.GroupLayout PanelPLayout = new javax.swing.GroupLayout(PanelP);
PanelP.setLayout(PanelPLayout);
PanelPLayout.setHorizontalGroup(
PanelPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 484, Short.MAX_VALUE)
);
PanelPLayout.setVerticalGroup(
PanelPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 435, Short.MAX_VALUE)
);
jButton1.setText("Mostrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jToggleButton1.setText("Salir");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
jButton2.setText("Recorrer");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(PanelP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
.addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(42, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(PanelP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jToggleButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addGap(18, 18, 18)
.addComponent(lPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// la idea es cuando se pulse el boton se cargue en el panel las imagenes del directorio indicado en el path.
String nombre,ruta = "C:/Users/ZOUHIR/Documents/Secuencia_imagenes/videofsom/frames/";
try {
File f = new File(ruta);
File[] ficheros = f.listFiles();
if (!f.exists()) {
System.out.println("No Existe el Directorio");
this.lPrincipal.setText("no existe Directorio");
} else {
// creo una coleccion de imagenes.
for (int i = 0; i < ficheros.length; i++) {
//leo la imagen del fichero.
imagen = ImageIO.read(ficheros[0]);
//imprimo el nombre para ver cual se esta leyendo.
nombre = ficheros[0].getName();
//BufferedImage buffered = (BufferedImage) imagen;
System.out.println(nombre);
//añado la imagen a la coleccion
Imagenes.add(imagen);
System.out.println("acabo de añadir a la coleccion la imagen "+0);
System.out.println("el numero de elementos de la coleccion "+ Imagenes.size());
//llamo al metodo que muesta la imagen en el panel.
// mostrarImagenes(Imagenes.get(i), nombre,i);
//this.esperar(5);
}
System.out.println("Imagenes del bucle cargadas en la coleccion-->salgo del bucle");
}
} catch (Exception ex) {
}
}
public void esperar(int segundos) {
try {
Thread.sleep(segundos * 1000);
} catch (Exception e) {
// Mensaje en caso de que falle
}
}
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// el evento relacionado con este boton es recorrer la coleccion.
System.out.println("tenemos antes de entrar en el bucle del recorrido");
for(int i=0;i<Imagenes.size();++i){
// recorro la coleccion entera
this.PanelP.setVisible(true);
this.mostrarImagenes(Imagenes.get(i),null , i);
this.esperar(5);
}
System.out.println("Finalizo el recorrido a toda la colecicon-->Deben aparecer laa imagenes en el panel");
}
public void mostrarImagenes(Image img, String nombre,int indice) {
// en este metodo muestro los elementos en el panel
//hago visible la etiqueta.
eq.setVisible(true);
Icon icono = new ImageIcon(img);
eq.setSize(200, 200);
eq.setIcon(icono);
System.out.println("He creado el icono de "+nombre + indice);
this.PanelP.setVisible(true);
this.PanelP.add(eq);
this.lPrincipal.setText("Cargando Imagen:" + nombre);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PanelCarga.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PanelCarga.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PanelCarga.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PanelCarga.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PanelCarga().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel PanelP;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JLabel lPrincipal;
// End of variables declaration
}
谢谢
答案 0 :(得分:3)
这是错误:
for (int i = 0; i < ficheros.length; i++) {
//leo la imagen del fichero.
imagen = ImageIO.read(ficheros[0]);
您始终只是阅读相同的图片,而不是i
。
相反它应该是这样的:
for (int i = 0; i < ficheros.length; i++) {
//leo la imagen del fichero.
imagen = ImageIO.read(ficheros[i]);
然而,迭代数组和集合的更好方法是:
for (String imageName : ficheros) {
imagen = ImageIO.read(imageName);
...
}
这种方法不仅更容易阅读,而且你绝对可以避免上述错误。