Partage
  • Partager sur Facebook
  • Partager sur Twitter

Problème de mise à jour affichage slideshow JPanel

    29 juillet 2022 à 15:31:20

    Bonjour à tous,

    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.

    Voici mon code avec la classe constructeur :

    package com.dug.plantId;
    
    /*** Constructor images DB ***/ 
    
    public class Plant {
    
        String id;
        byte[] image1, image2, image3, image4, image5;
    
        public Plant(
            byte[] image1, byte[] image2, byte[] image3, byte[] image4, byte[] image5, String id) {}
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public byte[] getImage1() {
            return image1;
        }
    
        public void setImage1(byte[] image1) {
            this.image1 = image1;
        }
    
        public byte[] getImage2() {
            return image2;
        }
    
        public void setImage2(byte[] image2) {
            this.image2 = image2;
        }
    
        public byte[] getImage3() {
            return image3;
        }
    
        public void setImage3(byte[] image3) {
            this.image3 = image3;
        }
    
        public byte[] getImage4() {
            return image4;
        }
    
        public void setImage4(byte[] image4) {
            this.image4 = image4;
        }
    
        public byte[] getImage5() {
            return image5;
        }
    
        public void setImage5(byte[] image5) {
            this.image5 = image5;
        }
    }

    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;
    
    public class DBConnection {
    
            private Connection connetion = null;
        private Statement stmt = null;
        private ResultSet rs = null;
    
        private MyPanels DBConnection;
    
        /*** Connexion à MySQL ***/
    
        public DBConnection() {
            try {
                this.connetion = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?" +
                    "user=Dug&password=Java427");
            } catch (SQLException ex) {
                // 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 ***/
    
        public List<Plant> searchPlant(String nom) {
            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(new Plant(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 (SQLException ex) {
                // handle any errors
                System.out.println("SQLException: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("VendorError: " + ex.getErrorCode());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
    
            }
            return listPlants;
        }
    
        /***  Méthodes pour générer des images de bases de données MySQL dans un dossier local (src) ***/
    
        public void image1Generate() throws SQLException, IOException {
    
            int i = rs.getInt("id");
            Blob ph = rs.getBlob("image1");
            if (ph == null) {
                return;
            }
            int length = (int) ph.length();
            int bufferSize = 1024;
            InputStream in = ph.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream outputStream = new FileOutputStream("src/photos/photo1.jpg");
            byte[] buffer = new byte[bufferSize];
    
            while ((length = in .read(buffer)) != -1) {
                System.out.println("writing " + length + " bytes");
                out.write(buffer, 0, length);
            }
            out.writeTo(outputStream); in .close();
        }
    
        public void image2Generate() throws SQLException, IOException {
    
            int i = rs.getInt("id");
            Blob ph = rs.getBlob("image2");
            if (ph == null) {
                return;
            }
            int length = (int) ph.length();
            int bufferSize = 1024;
            InputStream in = ph.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream outputStream = new FileOutputStream("src/photos/photo2.jpg");
            byte[] buffer = new byte[bufferSize];
            while ((length = in .read(buffer)) != -1) {
                System.out.println("writing " + length + " bytes");
                out.write(buffer, 0, length);
            }
            out.writeTo(outputStream); in .close();
        }
    
        public void WindowsMainPanelsAffichage() {
            DBConnection affichageImage = new DBConnection();
            affichageImage.DBConnection = new MyPanels();
        }
    
        public void image3Generate() throws SQLException, IOException {
    
            int i = rs.getInt("id");
            Blob ph = rs.getBlob("image3");
            if (ph == null) {
                return;
            }
            int length = (int) ph.length();
            int bufferSize = 1024;
            InputStream in = ph.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream outputStream = new FileOutputStream("src/photos/photo3.jpg");
            byte[] buffer = new byte[bufferSize];
            while ((length = in .read(buffer)) != -1) {
                System.out.println("writing " + length + " bytes");
                out.write(buffer, 0, length);
            }
            out.writeTo(outputStream); in .close();
        }
    
        public void image4Generate() throws SQLException, IOException {
    
            int i = rs.getInt("id");
            Blob ph = rs.getBlob("image4");
            if (ph == null) {
                return;
            }
            int length = (int) ph.length();
            int bufferSize = 1024;
            InputStream in = ph.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream outputStream = new FileOutputStream("src/photos/photo4.jpg");
            byte[] buffer = new byte[bufferSize];
            while ((length = in .read(buffer)) != -1) {
                System.out.println("writing " + length + " bytes");
                out.write(buffer, 0, length);
            }
            out.writeTo(outputStream); in .close();
        }
    
        public void image5Generate() throws SQLException, IOException {
    
            int i = rs.getInt("id");
            Blob ph = rs.getBlob("image5");
            if (ph == null) {
                return;
            }
            int length = (int) ph.length();
            int bufferSize = 1024;
            InputStream in = ph.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream outputStream = new FileOutputStream("src/photos/photo5.jpg");
            byte[] buffer = new byte[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;
    
    public class MyPanels extends JPanel implements ActionListener {
    
        private JComboBox jComboBoxNomCommun;
        private JComboBox jComboBoxNomLatin;
    
        static ImageIcon[] s;
        static JLabel jLabelImages;
        private static JButton b1;
        private static JButton b2;
        int i, l1;
    
        public MyPanels() {
            super();
            initComposantsPanel1();
        }
    
        /****  main ****/
    
        public static void main(String args[]) {
    
            MyPanels launchWindowsProg = new MyPanels();
            launchWindowsProg.generatePanels();
            launchWindowsProg.buttonsSlideShow();
        }
    
        /***  Initialiser les composants de panel1. ***/
    
        private void initComposantsPanel1() {
    
            this.setLayout(new GridBagLayout());
    
    
            JLabel listeAlphabetiqueNomLatin = panel1LabelCell(GridBagConstraints.WEST, 2, 1, "Liste alphabétique nom latin: ");
            jComboBoxNomLatin = panel1ComboBoxNomLatin(GridBagConstraints.WEST, 3, 1, "");
    
            
            JLabel listeAlphabetiqueNomCommunTextField = panel1LabelCell(GridBagConstraints.WEST, 2, 2, "Liste alphabétique nom commun: ");
            jComboBoxNomCommun = panel1ComboBoxNomCommun(GridBagConstraints.WEST, 3, 2, "");
        }
    
        /*** Constructeurs pour les différents composants ***/
    
        public JLabel panel1LabelCell(int GridBagConstraints, int positionGridx, int positionGridy, String labelLigne) {
            GridBagConstraints gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.insets = new Insets(0, 300, 3, 20);
            gridBagConstraints.anchor = GridBagConstraints;
            gridBagConstraints.gridx = positionGridx;
            gridBagConstraints.gridy = positionGridy;
            JLabel jLabel = new JLabel(labelLigne);
            this.add(jLabel, gridBagConstraints);
            return jLabel;
        }
    
        /*** Constructeur  panel1 (JComboBox) ***/
    
        public JComboBox panel1ComboBoxNomCommun(int GridBagConstraints, int positionGridx, int positionGridy, String text) {
            GridBagConstraints gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.anchor = GridBagConstraints;
            gridBagConstraints.ipadx = 10;
            JComboBox jComboBoxNomCommun = new JComboBox();
            jComboBoxNomCommun.setPreferredSize(new Dimension(225, 23));
            gridBagConstraints.gridx = positionGridx;
            gridBagConstraints.gridy = positionGridy;
    
            /*** DB connection ***/
    
            Connection con = null;
            Statement st = null;
            ResultSet rs = null;
    
            /*** Import liste DB vers jComboBoxNomCommun ***/
    
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?" +
                    "user=Dug&password=Java427");
                st = con.createStatement();
                String s = "select * from tblarbre";
                rs = st.executeQuery(s);
                while (rs.next()) {
                    jComboBoxNomCommun.addItem(rs.getString(
                        "nomCommun"));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "ERROR");
            } finally {
                try {
                    st.close();
                    rs.close();
                    con.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "ERROR CLOSE");
                }
            }
            
            jComboBoxNomCommun.addActionListener(e -> {
    
                String typedText = ((JTextField) jComboBoxNomCommun.getEditor().getEditorComponent()).getText();
    
                DBConnection dBConnection = new DBConnection();
                List<Plant> findedPlant = dBConnection.searchPlant(typedText);
    
                for (Plant plant: findedPlant) {
    
                }
            });
            this.add(jComboBoxNomCommun, gridBagConstraints);
            return jComboBoxNomCommun;
        }
        private JComboBox panel1ComboBoxNomLatin(int GridBagConstraints, int positionGridx, int positionGridy, String text) {
            GridBagConstraints gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.anchor = GridBagConstraints;
            gridBagConstraints.ipadx = 10;
            JComboBox jComboBoxNomLatin = new JComboBox();
            jComboBoxNomLatin.setPreferredSize(new Dimension(225, 23));
            gridBagConstraints.gridx = positionGridx;
            gridBagConstraints.gridy = positionGridy;
            this.add(jComboBoxNomLatin, gridBagConstraints);
    
            Connection con = null;
            Statement st = null;
            ResultSet rs = null;
    
            /***  Import liste DB to jComboBoxNomLatin ***/
    
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost/dbarbres?" +
                    "user=Dug&password=Java427");
                st = con.createStatement();
                String s = "select * from tblarbre";
                rs = st.executeQuery(s);
                while (rs.next()) {
                    jComboBoxNomLatin.addItem(rs.getString(
                        "nomLatin"));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "ERROR");
            } finally {
                try {
                    st.close();
                    rs.close();
                    con.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "ERROR CLOSE");
                }
            }
            jComboBoxNomLatin.addActionListener(e -> {
    
                String typedText = ((JTextField) jComboBoxNomLatin.getEditor().getEditorComponent()).getText();
    
                DBConnection dBConnection = new DBConnection();
                List<Plant> findedPlant = dBConnection.searchPlant(typedText);
    
                for (Plant plant: findedPlant) {
                }
            });
            return jComboBoxNomLatin;
        }
    
        /*** Generer les panels ***/
    
        void generatePanels() {
            SwingUtilities.invokeLater(() -> {
                JFrame frame = new JFrame();
                frame.setLayout(new BorderLayout());
                JPanel panel1 = new JPanel();
                JPanel panel2 = new JPanel();
                Border border = BorderFactory.createLineBorder(Color.GRAY, 1);
                panel1.setBounds(10, 10, 1400, 200);
                panel2.setBounds(720, 250, 700, 530);
                panel2.setBorder(border);
                MyPanels myPanels = new MyPanels();
                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 = new JLabel("", JLabel.CENTER);
                panel2.add(jLabelImages, BorderLayout.CENTER);
            });
        }
    
        /*** Import images dans une liste***/
    
        public static void imagesImportToList() {
            s = new ImageIcon[5];
            s[0] = new ImageIcon("src/photos/photo1.jpg");
            s[1] = new ImageIcon("src/photos/photo2.jpg");
            s[2] = new ImageIcon("src/photos/photo3.jpg");
            s[3] = new ImageIcon("src/photos/photo4.jpg");
            s[4] = new ImageIcon("src/photos/photo5.jpg");
        }
        /***  Methode pour afficher les images en diaporama avec les boutons "suivant "précédent" ***/
    
        public void buttonsSlideShow() {
    
            b1 = new JButton("<<");
            b2 = new JButton(">>");
    
            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
        public void actionPerformed(ActionEvent e) {}
    
        /*** Afficher l'image1 après la séléction dans la liste JCombobox  ***/
    
        static void displayImage1() {
            String displayImage1 = "src/photos/photo1.jpg";
            ImageIcon image1 = new ImageIcon(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.

    Merci d'avance pour votre éclairage.

    -
    Edité par Otherness 4 août 2022 à 21:41:53

    • Partager sur Facebook
    • Partager sur Twitter
      4 août 2022 à 17:49:04


      -
      Edité par Otherness 7 août 2022 à 17:03:53

      • Partager sur Facebook
      • Partager sur Twitter
        7 août 2022 à 16:58:20

        Otherness a écrit:

        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:

        image1 = new ImageIcon(ImageIO.read(new File("src/photos/photo1.jpg")));

        et préalablement ajouté en déclaration de variables:

        static ImageIcon image1;
        static ImageIcon image2;
        static ImageIcon image3;
        static ImageIcon image4;
        static ImageIcon image5;
        

        Voici le code pour la méthode image1Generate, il n'est pas nécessaire le créer les images dans un dossier:

        public void image1Generate() throws SQLException, IOException {
        
            Blob blob = rs.getBlob("image1");
        
            int blobLength = (int) blob.length();
        
            byte[] blobAsBytes = blob.getBytes(1, blobLength);
            final BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(blobAsBytes));
        
            image1 = (new ImageIcon(bufferedImage));
            }




        Puis j'ai modifié en conséquence la méthode imagesImportToList:

        public static void imagesImportToList() {
         
                s[0] = image1;
                s[1] = image2;
                s[2] = image3;
                s[3] = image4;
                s[4] = image5;
            }

        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;


        -
        Edité par Otherness il y a environ 17 heures



        -
        Edité par Otherness 7 août 2022 à 17:00:04

        • Partager sur Facebook
        • Partager sur Twitter

        Problème de mise à jour affichage slideshow JPanel

        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
        × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
        • Editeur
        • Markdown