From 4102a5bacfdf58ada8a25aec252c7e3e94576fbd Mon Sep 17 00:00:00 2001 From: kenfl Date: Mon, 31 Mar 2025 10:55:03 +0200 Subject: [PATCH] petite correction --- src/Main/inter.java | 435 +++++++++++++++++++++----------------------- 1 file changed, 211 insertions(+), 224 deletions(-) diff --git a/src/Main/inter.java b/src/Main/inter.java index dea8430..0bff3f5 100644 --- a/src/Main/inter.java +++ b/src/Main/inter.java @@ -4,8 +4,6 @@ import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; @@ -28,34 +26,33 @@ import javax.swing.BorderFactory; public class inter extends JFrame { - // Ajout du serialVersionUID private static final long serialVersionUID = 1L; + private static final int WINDOW_WIDTH = 600; + private static final int WINDOW_HEIGHT = 400; + private static final int MARGIN = 10; + private static final Font TITLE_FONT = new Font("Arial", Font.BOLD, 18); + private static final Font BUTTON_FONT = new Font("Arial", Font.BOLD, 24); + private static final Font NOTE_FONT = new Font("Arial", Font.BOLD, 24); private JPanel contentPane; private JPanel panel; private JButton entreeButton; - // Map pour stocker les listes de commentaires de chaque film - private Map> commentairesFilms = new HashMap<>(); - - // Map pour stocker les notes de chaque film - private Map notesFilms = new HashMap<>(); - - // Dictionnaire de mots avec leur sentiment - private Map dictionnaireSentiments = new HashMap<>(); + // Cache des données + private final Map> commentairesFilms = new HashMap<>(); + private final Map notesFilms = new HashMap<>(); + private final Map dictionnaireSentiments = new HashMap<>(); /** * Launch the application. */ public static void main(String[] args) { - EventQueue.invokeLater(new Runnable() { - public void run() { - try { - inter frame = new inter(); - frame.setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } + EventQueue.invokeLater(() -> { + try { + inter frame = new inter(); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); } }); } @@ -64,105 +61,96 @@ public class inter extends JFrame { * Create the frame. */ public inter() { - // Initialiser le dictionnaire de sentiments initialiserDictionnaireSentiments(); - + initialiserInterface(); + } + + /** + * Initialise l'interface utilisateur + */ + private void initialiserInterface() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setBounds(100, 100, 600, 400); // Augmenter la taille de la fenêtre + setBounds(100, 100, WINDOW_WIDTH, WINDOW_HEIGHT); + contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); panel = new JPanel(); - panel.setLayout(new BorderLayout()); // Changer le layout pour centrer le bouton + panel.setLayout(new BorderLayout()); contentPane.add(panel, BorderLayout.CENTER); // Création du bouton initial - entreeButton = new JButton("Entrée"); - entreeButton.setFont(new Font("Arial", Font.BOLD, 24)); // Augmenter la taille de la police + entreeButton = new JButton("Entrer"); + entreeButton.setFont(BUTTON_FONT); - // Créer un panel pour contenir le bouton et ajouter des marges + // Panel pour contenir le bouton avec marges JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); - buttonPanel.setBorder(new EmptyBorder(80, 150, 80, 150)); // Ajouter des marges (haut, gauche, bas, droite) + buttonPanel.setBorder(new EmptyBorder(80, 150, 80, 150)); buttonPanel.add(entreeButton, BorderLayout.CENTER); panel.add(buttonPanel, BorderLayout.CENTER); - // Action du bouton initial - Afficher directement les 10 carrés noirs - entreeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Afficher directement les 10 carrés noirs - afficherFilms(); - } - }); + // Action du bouton initial + entreeButton.addActionListener(e -> afficherFilms()); } /** - * Initialise un dictionnaire simple de mots avec leur sentiment + * Initialise le dictionnaire de sentiments */ private void initialiserDictionnaireSentiments() { // Mots positifs - dictionnaireSentiments.put("aime", 80); - dictionnaireSentiments.put("bien", 70); - dictionnaireSentiments.put("super", 90); - dictionnaireSentiments.put("excellent", 95); - dictionnaireSentiments.put("génial", 90); - dictionnaireSentiments.put("bon", 75); - dictionnaireSentiments.put("agréable", 65); - dictionnaireSentiments.put("intéressant", 60); - dictionnaireSentiments.put("beau", 70); - dictionnaireSentiments.put("magnifique", 85); + String[] motsPositifs = {"aime", "bien", "super", "excellent", "génial", "bon", + "agréable", "intéressant", "beau", "magnifique"}; + int[] valeursPositives = {80, 70, 90, 95, 90, 75, 65, 60, 70, 85}; // Mots négatifs - dictionnaireSentiments.put("mauvais", 20); - dictionnaireSentiments.put("nul", 10); - dictionnaireSentiments.put("horrible", 5); - dictionnaireSentiments.put("déteste", 10); - dictionnaireSentiments.put("ennuyeux", 25); - dictionnaireSentiments.put("décevant", 30); - dictionnaireSentiments.put("médiocre", 35); - dictionnaireSentiments.put("pire", 15); - dictionnaireSentiments.put("terrible", 20); - dictionnaireSentiments.put("affreux", 15); + String[] motsNegatifs = {"mauvais", "nul", "horrible", "déteste", "ennuyeux", + "décevant", "médiocre", "pire", "terrible", "affreux"}; + int[] valeursNegatives = {20, 10, 5, 10, 25, 30, 35, 15, 20, 15}; + + // Remplir le dictionnaire + for (int i = 0; i < motsPositifs.length; i++) { + dictionnaireSentiments.put(motsPositifs[i], valeursPositives[i]); + } + + for (int i = 0; i < motsNegatifs.length; i++) { + dictionnaireSentiments.put(motsNegatifs[i], valeursNegatives[i]); + } } /** - * Méthode pour afficher les 10 carrés noirs avec les textes "Film 1", "Film 2", ..., "Film 10". + * Affiche la grille des 10 films */ private void afficherFilms() { - // Effacer les composants actuels panel.removeAll(); - // Utiliser un BorderLayout pour organiser les carrés et le bouton retour - panel.setLayout(new BorderLayout(0, 10)); // Ajouter un espacement vertical - panel.setBorder(new EmptyBorder(10, 10, 10, 10)); // Ajouter des marges + panel.setLayout(new BorderLayout(0, MARGIN)); + panel.setBorder(new EmptyBorder(MARGIN, MARGIN, MARGIN, MARGIN)); - // Ajouter un titre en haut + // Titre JLabel titreLabel = new JLabel("10 films qui pourraient vous plaire"); - titreLabel.setFont(new Font("Arial", Font.BOLD, 18)); + titreLabel.setFont(TITLE_FONT); titreLabel.setHorizontalAlignment(SwingConstants.CENTER); panel.add(titreLabel, BorderLayout.NORTH); - // Panel pour les carrés noirs + // Grille de films JPanel gridPanel = new JPanel(); - gridPanel.setLayout(new GridLayout(2, 5, 10, 10)); // 2 lignes, 5 colonnes, espacement de 10px + gridPanel.setLayout(new GridLayout(2, 5, MARGIN, MARGIN)); - // Ajouter les 10 carrés noirs avec les textes for (int i = 1; i <= 10; i++) { - final int filmNumber = i; // Variable finale pour utiliser dans le listener + final int filmNumber = i; JPanel filmPanel = new JPanel(); - filmPanel.setLayout(new BoxLayout(filmPanel, BoxLayout.Y_AXIS)); // Disposition verticale + filmPanel.setLayout(new BoxLayout(filmPanel, BoxLayout.Y_AXIS)); // Carré noir JPanel carre = new JPanel(); carre.setSize(50, 50); carre.setBackground(java.awt.Color.BLACK); - // Ajouter un écouteur de clic sur le carré noir carre.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { @@ -172,7 +160,7 @@ public class inter extends JFrame { filmPanel.add(carre); - // Texte en dessous + // Texte du film JLabel label = new JLabel("Film " + filmNumber); label.setHorizontalAlignment(SwingConstants.CENTER); filmPanel.add(label); @@ -180,41 +168,40 @@ public class inter extends JFrame { gridPanel.add(filmPanel); } - // Ajouter le panel des carrés au centre panel.add(gridPanel, BorderLayout.CENTER); - // Ajouter le bouton retour en bas + // Bouton retour JButton retourBas = new JButton("Retour"); - retourBas.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Revenir à l'écran initial - panel.removeAll(); - panel.setLayout(new BorderLayout()); - - // Recréer le bouton initial avec son panel de marges - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new BorderLayout()); - buttonPanel.setBorder(new EmptyBorder(80, 150, 80, 150)); - buttonPanel.add(entreeButton, BorderLayout.CENTER); - panel.add(buttonPanel, BorderLayout.CENTER); - - panel.revalidate(); - panel.repaint(); - } - }); + retourBas.addActionListener(e -> afficherEcranInitial()); panel.add(retourBas, BorderLayout.SOUTH); - // Rafraîchir l'affichage - panel.revalidate(); - panel.repaint(); + rafraichirPanel(); } /** - * Méthode pour analyser un commentaire et calculer une note sur 5 + * Affiche l'écran initial avec le bouton Entrer + */ + private void afficherEcranInitial() { + panel.removeAll(); + panel.setLayout(new BorderLayout()); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new BorderLayout()); + buttonPanel.setBorder(new EmptyBorder(80, 150, 80, 150)); + buttonPanel.add(entreeButton, BorderLayout.CENTER); + panel.add(buttonPanel, BorderLayout.CENTER); + + rafraichirPanel(); + } + + /** + * Analyse un commentaire et calcule une note sur 5 */ private int analyserCommentaire(String commentaire) { - // Tokeniser le commentaire en mots + if (commentaire == null || commentaire.trim().isEmpty()) { + return 3; // Note moyenne par défaut + } + StringTokenizer tokenizer = new StringTokenizer(commentaire.toLowerCase(), " ,.!?;:()\n\t\"'"); int totalSentiment = 0; @@ -223,93 +210,122 @@ public class inter extends JFrame { while (tokenizer.hasMoreTokens()) { String mot = tokenizer.nextToken(); - // Vérifier si le mot est dans le dictionnaire - if (dictionnaireSentiments.containsKey(mot)) { - totalSentiment += dictionnaireSentiments.get(mot); + Integer sentiment = dictionnaireSentiments.get(mot); + if (sentiment != null) { + totalSentiment += sentiment; nbMots++; } } - // Si aucun mot du commentaire n'est dans le dictionnaire, retourner une note moyenne if (nbMots == 0) { - return 3; + return 3; // Note moyenne par défaut } - // Calculer la moyenne des sentiments + // Calculer la note double moyenneSentiment = (double) totalSentiment / nbMots; - - // Convertir en note sur 5 int note = (int) Math.round(moyenneSentiment * 5 / 100); - // S'assurer que la note est entre 1 et 5 - note = Math.max(1, Math.min(5, note)); - - return note; + // Limiter entre 1 et 5 + return Math.max(1, Math.min(5, note)); } /** - * Méthode pour calculer la note moyenne d'un film basée sur tous ses commentaires + * Calcule la note moyenne d'un film basée sur tous ses commentaires */ private int calculerNoteMoyenne(int filmNumber) { List commentaires = commentairesFilms.get(filmNumber); if (commentaires == null || commentaires.isEmpty()) { - return 0; // Pas de note si pas de commentaires + return 0; } int totalNotes = 0; - // Analyser chaque commentaire et additionner les notes for (String commentaire : commentaires) { totalNotes += analyserCommentaire(commentaire); } - // Calculer la moyenne return Math.round((float) totalNotes / commentaires.size()); } /** - * Méthode pour afficher les détails d'un film + * Affiche les détails d'un film */ private void afficherDetailFilm(int filmNumber) { - // Effacer les composants actuels panel.removeAll(); - // Utiliser un BorderLayout pour organiser la page de détail - panel.setLayout(new BorderLayout(10, 10)); - panel.setBorder(new EmptyBorder(10, 10, 10, 10)); - - // Partie gauche : image du film (pour l'instant un panel noir) - JPanel imagePanel = new JPanel(); - imagePanel.setBackground(java.awt.Color.BLACK); - imagePanel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); - imagePanel.setPreferredSize(new java.awt.Dimension(150, 200)); - - // Ajouter le texte "Film X (image)" au panel de l'image - JLabel imageLabel = new JLabel("Film " + filmNumber + " (image)"); - imageLabel.setForeground(java.awt.Color.WHITE); - imageLabel.setHorizontalAlignment(SwingConstants.CENTER); - imagePanel.setLayout(new BorderLayout()); - imagePanel.add(imageLabel, BorderLayout.CENTER); + panel.setLayout(new BorderLayout(MARGIN, MARGIN)); + panel.setBorder(new EmptyBorder(MARGIN, MARGIN, MARGIN, MARGIN)); + // Partie gauche : image du film + JPanel imagePanel = creerPanelImage(filmNumber); panel.add(imagePanel, BorderLayout.WEST); // Partie droite : informations sur le film JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new BorderLayout(10, 10)); + infoPanel.setLayout(new BorderLayout(MARGIN, MARGIN)); // Titre du film JLabel titreLabel = new JLabel("Titre + Infos"); - titreLabel.setFont(new Font("Arial", Font.BOLD, 16)); + titreLabel.setFont(TITLE_FONT); titreLabel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); titreLabel.setHorizontalAlignment(SwingConstants.CENTER); infoPanel.add(titreLabel, BorderLayout.NORTH); // Partie centrale avec note et commentaires JPanel centralPanel = new JPanel(); - centralPanel.setLayout(new GridLayout(1, 2, 10, 0)); + centralPanel.setLayout(new GridLayout(1, 2, MARGIN, 0)); - // Panel pour la note et le commentaire affiché + // Initialiser la liste des commentaires si nécessaire + if (!commentairesFilms.containsKey(filmNumber)) { + commentairesFilms.put(filmNumber, new ArrayList<>()); + } + + List commentaires = commentairesFilms.get(filmNumber); + + // Panel pour la note et les commentaires affichés + JPanel notePanel = creerPanelNote(filmNumber, commentaires); + + // Panel pour la saisie des commentaires + JPanel commentPanel = creerPanelSaisieCommentaire(filmNumber); + + centralPanel.add(notePanel); + centralPanel.add(commentPanel); + + infoPanel.add(centralPanel, BorderLayout.CENTER); + + panel.add(infoPanel, BorderLayout.CENTER); + + // Bouton retour en bas + JButton retourButton = new JButton("Retour"); + retourButton.addActionListener(e -> afficherFilms()); + panel.add(retourButton, BorderLayout.SOUTH); + + rafraichirPanel(); + } + + /** + * Crée le panel d'image pour un film + */ + private JPanel creerPanelImage(int filmNumber) { + JPanel imagePanel = new JPanel(); + imagePanel.setBackground(java.awt.Color.BLACK); + imagePanel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); + imagePanel.setPreferredSize(new java.awt.Dimension(150, 200)); + + JLabel imageLabel = new JLabel("Film " + filmNumber + " (image)"); + imageLabel.setForeground(java.awt.Color.WHITE); + imageLabel.setHorizontalAlignment(SwingConstants.CENTER); + imagePanel.setLayout(new BorderLayout()); + imagePanel.add(imageLabel, BorderLayout.CENTER); + + return imagePanel; + } + + /** + * Crée le panel de note et d'affichage des commentaires + */ + private JPanel creerPanelNote(int filmNumber, List commentaires) { JPanel notePanel = new JPanel(); notePanel.setLayout(new BorderLayout()); notePanel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); @@ -321,16 +337,10 @@ public class inter extends JFrame { // Label pour afficher la note calculée JLabel noteValueLabel = new JLabel(); - noteValueLabel.setFont(new Font("Arial", Font.BOLD, 24)); + noteValueLabel.setFont(NOTE_FONT); noteValueLabel.setHorizontalAlignment(SwingConstants.CENTER); - // Initialiser la liste des commentaires si elle n'existe pas encore - if (!commentairesFilms.containsKey(filmNumber)) { - commentairesFilms.put(filmNumber, new ArrayList<>()); - } - - // Calculer et afficher la note moyenne si des commentaires existent - List commentaires = commentairesFilms.get(filmNumber); + // Calculer et afficher la note moyenne if (!commentaires.isEmpty()) { int noteMoyenne = calculerNoteMoyenne(filmNumber); notesFilms.put(filmNumber, noteMoyenne); @@ -343,11 +353,7 @@ public class inter extends JFrame { noteValuePanel.setLayout(new BorderLayout()); noteValuePanel.add(noteValueLabel, BorderLayout.NORTH); - // Panel pour contenir les commentaires affichés - JPanel commentDisplayPanel = new JPanel(); - commentDisplayPanel.setLayout(new BorderLayout()); - - // Zone de texte pour afficher les commentaires + // Zone d'affichage des commentaires JTextArea commentDisplayArea = new JTextArea(); commentDisplayArea.setEditable(false); commentDisplayArea.setLineWrap(true); @@ -356,17 +362,25 @@ public class inter extends JFrame { // Afficher tous les commentaires existants StringBuilder sb = new StringBuilder(); for (int i = 0; i < commentaires.size(); i++) { - sb.append("Commentaire ").append(i + 1).append(" : ").append(commentaires.get(i)).append("\n\n"); + sb.append("Commentaire ").append(i + 1).append(" : ") + .append(commentaires.get(i)).append("\n\n"); } commentDisplayArea.setText(sb.toString()); JScrollPane commentDisplayScroll = new JScrollPane(commentDisplayArea); + JPanel commentDisplayPanel = new JPanel(new BorderLayout()); commentDisplayPanel.add(commentDisplayScroll, BorderLayout.CENTER); noteValuePanel.add(commentDisplayPanel, BorderLayout.CENTER); notePanel.add(noteValuePanel, BorderLayout.CENTER); - // Panel pour la saisie des commentaires + return notePanel; + } + + /** + * Crée le panel de saisie des commentaires + */ + private JPanel creerPanelSaisieCommentaire(int filmNumber) { JPanel commentPanel = new JPanel(); commentPanel.setLayout(new BorderLayout(0, 5)); commentPanel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLACK)); @@ -382,93 +396,66 @@ public class inter extends JFrame { commentArea.setLineWrap(true); commentArea.setWrapStyleWord(true); - // Ajouter un JScrollPane pour permettre le défilement JScrollPane scrollPane = new JScrollPane(commentArea); commentPanel.add(scrollPane, BorderLayout.CENTER); // Bouton pour enregistrer le commentaire - JButton saveButton = new JButton("Entrée"); - saveButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Récupérer le commentaire - String commentaire = commentArea.getText(); - - if (commentaire.trim().isEmpty()) { - JOptionPane.showMessageDialog(panel, "Veuillez entrer un commentaire.", "Erreur", JOptionPane.ERROR_MESSAGE); - return; - } - - // Afficher la boîte de dialogue de confirmation - int reponse = JOptionPane.showConfirmDialog( - panel, - "Êtes-vous sûr ?", - "Confirmation", - JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE - ); - - // Si l'utilisateur clique sur "Oui" - if (reponse == JOptionPane.YES_OPTION) { - // Ajouter le commentaire à la liste - commentairesFilms.get(filmNumber).add(commentaire); - - // Calculer la note moyenne basée sur tous les commentaires - int noteMoyenne = calculerNoteMoyenne(filmNumber); - - // Enregistrer la note - notesFilms.put(filmNumber, noteMoyenne); - - // Mettre à jour l'affichage de la note - noteValueLabel.setText(noteMoyenne + "/5"); - - // Mettre à jour l'affichage des commentaires - List commentaires = commentairesFilms.get(filmNumber); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < commentaires.size(); i++) { - sb.append("Commentaire ").append(i + 1).append(" : ").append(commentaires.get(i)).append("\n\n"); - } - commentDisplayArea.setText(sb.toString()); - - // Faire défiler vers le bas pour voir le nouveau commentaire - commentDisplayArea.setCaretPosition(commentDisplayArea.getText().length()); - - // Vider la zone de texte de saisie - commentArea.setText(""); - - // Afficher un message de confirmation avec la note - JOptionPane.showMessageDialog(panel, - "Commentaire ajouté avec succès !\nNote moyenne du film : " + noteMoyenne + "/5", - "Succès", - JOptionPane.INFORMATION_MESSAGE); - - // Rafraîchir l'affichage - notePanel.revalidate(); - notePanel.repaint(); - } - // Si l'utilisateur clique sur "Non", ne rien faire + JButton saveButton = new JButton("Entrer"); + saveButton.addActionListener(e -> { + String commentaire = commentArea.getText(); + + if (commentaire.trim().isEmpty()) { + JOptionPane.showMessageDialog(panel, + "Veuillez entrer un commentaire.", + "Erreur", + JOptionPane.ERROR_MESSAGE); + return; + } + + int reponse = JOptionPane.showConfirmDialog( + panel, + "Êtes-vous sûr ?", + "Confirmation", + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE + ); + + if (reponse == JOptionPane.YES_OPTION) { + ajouterCommentaire(filmNumber, commentaire); + commentArea.setText(""); } }); commentPanel.add(saveButton, BorderLayout.SOUTH); - centralPanel.add(notePanel); - centralPanel.add(commentPanel); + return commentPanel; + } + + /** + * Ajoute un commentaire à un film et met à jour l'interface + */ + private void ajouterCommentaire(int filmNumber, String commentaire) { + // Récupérer la liste des commentaires + List commentaires = commentairesFilms.get(filmNumber); + commentaires.add(commentaire); - infoPanel.add(centralPanel, BorderLayout.CENTER); + // Calculer la nouvelle note moyenne + int noteMoyenne = calculerNoteMoyenne(filmNumber); + notesFilms.put(filmNumber, noteMoyenne); - panel.add(infoPanel, BorderLayout.CENTER); + // Mettre à jour l'interface + afficherDetailFilm(filmNumber); - // Bouton retour en bas - JButton retourButton = new JButton("Retour"); - retourButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - afficherFilms(); - } - }); - panel.add(retourButton, BorderLayout.SOUTH); - - // Rafraîchir l'affichage + // Afficher un message de confirmation + JOptionPane.showMessageDialog(panel, + "Commentaire ajouté avec succès !\nNote moyenne du film : " + noteMoyenne + "/5", + "Succès", + JOptionPane.INFORMATION_MESSAGE); + } + + /** + * Rafraîchit l'affichage du panel principal + */ + private void rafraichirPanel() { panel.revalidate(); panel.repaint(); }