Problème de mise à jour affichage slideshow dans JPanel
Fermé
otherness
Messages postés486Date d'inscriptionmardi 25 janvier 2005StatutMembreDernière intervention24 décembre 2024
-
2 août 2022 à 10:19
otherness
Messages postés486Date d'inscriptionmardi 25 janvier 2005StatutMembreDernière intervention24 décembre 2024
-
7 août 2022 à 17:07
Bonjour,
Je suis un débutant en Java et je réalise un petit projet qui consiste à afficher des images de plantes avec JComBox à partir d'une base de données MySQL et un JLabel pour afficher un diaporama d'images.
Pour les images, je dois les importer dans un dossier local src/... et pour cela j'utilise une méthode byteArrayOutputStream qui fonctionne bien.
Lorsque je sélectionne un élément de la liste pour la première fois, les images sont bien affichées dans le JLabel et le silideshow fonctionne bien avec les boutons.
Par contre lorsque je change de sélection dans ma liste, mes informations sont bien changées dans les différents JTextField mais ce sont toujours les mêmes images de la première sélection qui sont affichées dans mon diaporama et pourtant elles sont bien changées dans le fichier source.
Classe avec le code pour la connexion à la DB et l'affacturage des images dans un dossier (src)
package com.dug.plantId;import java.io.*;import java.sql.*;import java.util.ArrayList;import java.util.List;publicclassDBConnection{privateConnectionconnetion =null;privateStatementstmt =null;privateResultSetrs =null;privateMyPanelsDBConnection;/*** Connexion à MySQL ***/publicDBConnection(){try{this.connetion = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?"+"user=Dug&password=Java427");}catch(SQLExceptionex){// handle any errors
System.out.println("SQLException: "+ ex.getMessage());
System.out.println("SQLState: "+ ex.getSQLState());
System.out.println("VendorError: "+ ex.getErrorCode());}}/*** Méthode pour créer une liste importée de la BD ***/publicList<Plant>searchPlant(Stringnom){List<Plant>listPlants =new ArrayList<Plant>();try{
stmt = connetion.createStatement();
rs = stmt.executeQuery("SELECT * FROM dbarbres.tblarbre where nomLatin like '%"+ nom +"%' or nomCommun like '%"+ nom +"%'");byte[] image =null;while(rs.next()){
listPlants.add(newPlant(rs.getBytes("image1"), rs.getBytes("image2"),
rs.getBytes("image3"), rs.getBytes("image4"), rs.getBytes("image5"), rs.getInt("id")+""));/*** Appel des méthodes de FileOutputStream pour afficher les images de la BD. ***/image1Generate();image2Generate();image3Generate();image4Generate();image5Generate();
MyPanels.imagesImportToList();/*** Appelez une méthode statique pour afficher la première image ***/
MyPanels.displayImage1();}}catch(SQLExceptionex){// handle any errors
System.out.println("SQLException: "+ ex.getMessage());
System.out.println("SQLState: "+ ex.getSQLState());
System.out.println("VendorError: "+ ex.getErrorCode());}catch(FileNotFoundExceptione){
e.printStackTrace();}catch(IOExceptione){}return listPlants;}/*** Méthodes pour générer des images de bases de données MySQL dans un dossier local (src) ***/publicvoidimage1Generate()throws SQLException, IOException {int i = rs.getInt("id");Blobph = rs.getBlob("image1");if(ph ==null){return;}int length =(int) ph.length();int bufferSize =1024;InputStreamin = ph.getBinaryStream();ByteArrayOutputStreamout =newByteArrayOutputStream();OutputStreamoutputStream =newFileOutputStream("src/photos/photo1.jpg");byte[] buffer =newbyte[bufferSize];while((length = in .read(buffer))!=-1){
System.out.println("writing "+ length +" bytes");
out.write(buffer,0, length);}
out.writeTo(outputStream); in .close();}publicvoidimage2Generate()throws SQLException, IOException {int i = rs.getInt("id");Blobph = rs.getBlob("image2");if(ph ==null){return;}int length =(int) ph.length();int bufferSize =1024;InputStreamin = ph.getBinaryStream();ByteArrayOutputStreamout =newByteArrayOutputStream();OutputStreamoutputStream =newFileOutputStream("src/photos/photo2.jpg");byte[] buffer =newbyte[bufferSize];while((length = in .read(buffer))!=-1){
System.out.println("writing "+ length +" bytes");
out.write(buffer,0, length);}
out.writeTo(outputStream); in .close();}publicvoidWindowsMainPanelsAffichage(){DBConnectionaffichageImage =newDBConnection();
affichageImage.DBConnection =newMyPanels();}publicvoidimage3Generate()throws SQLException, IOException {int i = rs.getInt("id");Blobph = rs.getBlob("image3");if(ph ==null){return;}int length =(int) ph.length();int bufferSize =1024;InputStreamin = ph.getBinaryStream();ByteArrayOutputStreamout =newByteArrayOutputStream();OutputStreamoutputStream =newFileOutputStream("src/photos/photo3.jpg");byte[] buffer =newbyte[bufferSize];while((length = in .read(buffer))!=-1){
System.out.println("writing "+ length +" bytes");
out.write(buffer,0, length);}
out.writeTo(outputStream); in .close();}publicvoidimage4Generate()throws SQLException, IOException {int i = rs.getInt("id");Blobph = rs.getBlob("image4");if(ph ==null){return;}int length =(int) ph.length();int bufferSize =1024;InputStreamin = ph.getBinaryStream();ByteArrayOutputStreamout =newByteArrayOutputStream();OutputStreamoutputStream =newFileOutputStream("src/photos/photo4.jpg");byte[] buffer =newbyte[bufferSize];while((length = in .read(buffer))!=-1){
System.out.println("writing "+ length +" bytes");
out.write(buffer,0, length);}
out.writeTo(outputStream); in .close();}publicvoidimage5Generate()throws SQLException, IOException {int i = rs.getInt("id");Blobph = rs.getBlob("image5");if(ph ==null){return;}int length =(int) ph.length();int bufferSize =1024;InputStreamin = ph.getBinaryStream();ByteArrayOutputStreamout =newByteArrayOutputStream();OutputStreamoutputStream =newFileOutputStream("src/photos/photo5.jpg");byte[] buffer =newbyte[bufferSize];while((length = in .read(buffer))!=-1){
System.out.println("writing "+ length +" bytes");
out.write(buffer,0, length);}
out.writeTo(outputStream); in .close();}}
Classe avec code pour générer des cadres, des panneaux, des jlabel pour les images et des boutons pour le diaporama.
package com.dug.plantId;import javax.swing.*;import javax.swing.border.Border;import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.List;publicclassMyPanelsextends JPanel implements ActionListener {privateJComboBoxjComboBoxNomCommun;privateJComboBoxjComboBoxNomLatin;static ImageIcon[] s;staticJLabeljLabelImages;privatestaticJButtonb1;privatestaticJButtonb2;int i, l1;publicMyPanels(){super();initComposantsPanel1();}/**** main ****/publicstaticvoidmain(Stringargs[]){MyPanelslaunchWindowsProg =newMyPanels();
launchWindowsProg.generatePanels();
launchWindowsProg.buttonsSlideShow();}/*** Initialiser les composants de panel1. ***/privatevoidinitComposantsPanel1(){this.setLayout(newGridBagLayout());JLabellisteAlphabetiqueNomLatin =panel1LabelCell(GridBagConstraints.WEST,2,1,"Liste alphabétique nom latin: ");
jComboBoxNomLatin =panel1ComboBoxNomLatin(GridBagConstraints.WEST,3,1,"");JLabellisteAlphabetiqueNomCommunTextField =panel1LabelCell(GridBagConstraints.WEST,2,2,"Liste alphabétique nom commun: ");
jComboBoxNomCommun =panel1ComboBoxNomCommun(GridBagConstraints.WEST,3,2,"");}/*** Constructeurs pour les différents composants ***/publicJLabelpanel1LabelCell(int GridBagConstraints,int positionGridx,int positionGridy,StringlabelLigne){GridBagConstraintsgridBagConstraints =newGridBagConstraints();
gridBagConstraints.insets =newInsets(0,300,3,20);
gridBagConstraints.anchor = GridBagConstraints;
gridBagConstraints.gridx = positionGridx;
gridBagConstraints.gridy = positionGridy;JLabeljLabel =newJLabel(labelLigne);this.add(jLabel, gridBagConstraints);return jLabel;}/*** Constructeur panel1 (JComboBox) ***/publicJComboBoxpanel1ComboBoxNomCommun(int GridBagConstraints,int positionGridx,int positionGridy,Stringtext){GridBagConstraintsgridBagConstraints =newGridBagConstraints();
gridBagConstraints.anchor = GridBagConstraints;
gridBagConstraints.ipadx =10;JComboBoxjComboBoxNomCommun =newJComboBox();
jComboBoxNomCommun.setPreferredSize(newDimension(225,23));
gridBagConstraints.gridx = positionGridx;
gridBagConstraints.gridy = positionGridy;/*** DB connection ***/Connectioncon =null;Statementst =null;ResultSetrs =null;/*** Import liste DB vers jComboBoxNomCommun ***/try{
con = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?"+"user=Dug&password=Java427");
st = con.createStatement();Strings ="select * from tblarbre";
rs = st.executeQuery(s);while(rs.next()){
jComboBoxNomCommun.addItem(rs.getString("nomCommun"));}}catch(Exceptione){
JOptionPane.showMessageDialog(null,"ERROR");}finally{try{
st.close();
rs.close();
con.close();}catch(Exceptione){
JOptionPane.showMessageDialog(null,"ERROR CLOSE");}}
jComboBoxNomCommun.addActionListener(e ->{StringtypedText =((JTextField) jComboBoxNomCommun.getEditor().getEditorComponent()).getText();DBConnectiondBConnection =newDBConnection();List<Plant>findedPlant = dBConnection.searchPlant(typedText);for(Plantplant: findedPlant){}});this.add(jComboBoxNomCommun, gridBagConstraints);return jComboBoxNomCommun;}privateJComboBoxpanel1ComboBoxNomLatin(int GridBagConstraints,int positionGridx,int positionGridy,Stringtext){GridBagConstraintsgridBagConstraints =newGridBagConstraints();
gridBagConstraints.anchor = GridBagConstraints;
gridBagConstraints.ipadx =10;JComboBoxjComboBoxNomLatin =newJComboBox();
jComboBoxNomLatin.setPreferredSize(newDimension(225,23));
gridBagConstraints.gridx = positionGridx;
gridBagConstraints.gridy = positionGridy;this.add(jComboBoxNomLatin, gridBagConstraints);Connectioncon =null;Statementst =null;ResultSetrs =null;/*** Import liste DB to jComboBoxNomLatin ***/try{
con = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?"+"user=Dug&password=Java427");
st = con.createStatement();Strings ="select * from tblarbre";
rs = st.executeQuery(s);while(rs.next()){
jComboBoxNomLatin.addItem(rs.getString("nomLatin"));}}catch(Exceptione){
JOptionPane.showMessageDialog(null,"ERROR");}finally{try{
st.close();
rs.close();
con.close();}catch(Exceptione){
JOptionPane.showMessageDialog(null,"ERROR CLOSE");}}
jComboBoxNomLatin.addActionListener(e ->{StringtypedText =((JTextField) jComboBoxNomLatin.getEditor().getEditorComponent()).getText();DBConnectiondBConnection =newDBConnection();List<Plant>findedPlant = dBConnection.searchPlant(typedText);for(Plantplant: findedPlant){}});return jComboBoxNomLatin;}/*** Generer les panels ***/voidgeneratePanels(){
SwingUtilities.invokeLater(()->{JFrameframe =newJFrame();
frame.setLayout(newBorderLayout());JPanelpanel1 =newJPanel();JPanelpanel2 =newJPanel();Borderborder = BorderFactory.createLineBorder(Color.GRAY,1);
panel1.setBounds(10,10,1400,200);
panel2.setBounds(720,250,700,530);
panel2.setBorder(border);MyPanelsmyPanels =newMyPanels();
panel1.add(myPanels);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(1450,900);
frame.setVisible(true);/*** Ajout des buttons pour showview images***/
panel2.add(b1);
panel2.add(b2);
jLabelImages =newJLabel("", JLabel.CENTER);
panel2.add(jLabelImages, BorderLayout.CENTER);});}/*** Import images dans une liste***/publicstaticvoidimagesImportToList(){
s =new ImageIcon[5];
s[0]=newImageIcon("src/photos/photo1.jpg");
s[1]=newImageIcon("src/photos/photo2.jpg");
s[2]=newImageIcon("src/photos/photo3.jpg");
s[3]=newImageIcon("src/photos/photo4.jpg");
s[4]=newImageIcon("src/photos/photo5.jpg");}/*** Methode pour afficher les images en diaporama avec les boutons "suivant "précédent" ***/publicvoidbuttonsSlideShow(){
b1 =newJButton("<<");
b2 =newJButton(">>");
b1.addActionListener(e ->{if(e.getSource()== b1){if(i ==0){
JOptionPane.showMessageDialog(null," First image");}else{
i = i -1;
jLabelImages.setIcon(s[i]);}}if(e.getSource()== b2){if(i == s.length -1){
JOptionPane.showMessageDialog(null,"Last Image");}else{
i = i +1;
jLabelImages.setIcon(s[i]);}}});
b2.addActionListener(e ->{if(e.getSource()== b1){if(i ==0){
JOptionPane.showMessageDialog(null,"First image");}else{
i = i -1;
jLabelImages.setIcon(s[i]);}}if(e.getSource()== b2){if(i == s.length -1){
JOptionPane.showMessageDialog(null,"Last Image");}else{
i = i +1;
jLabelImages.setIcon(s[i]);}}});}
@Override
publicvoidactionPerformed(ActionEvente){}/*** Afficher l'image1 après la séléction dans la liste JCombobox ***/staticvoiddisplayImage1(){StringdisplayImage1 ="src/photos/photo1.jpg";ImageIconimage1 =newImageIcon(displayImage1);
jLabelImages.setIcon(image1);}}
J'ai tout essayé mais je n'y arrive pas, il y aurait peut-être une solution avec ressource intégrée via une URL. Une URL qui peut être obtenue en utilisant Class.getResource() mais je n'ai pas assez de connaissances.
otherness
Messages postés486Date d'inscriptionmardi 25 janvier 2005StatutMembreDernière intervention24 décembre 202432 6 août 2022 à 23:42
J'ai finalement trouvé la solution, j'ai créé un objet ImageIcon pour chaque image générée dans le dossier src, j'ai donc rajouté cette ligne dans chacune des méthodes imageGenerate:
et pour finir, afin que mon diaporama ne s'emmêle pas les pinceaux et revenir à l'image1 à chaque changement , j'ai ajouté là où il était nécessaire: i = 0;