Probleme interface java

Résolu/Fermé
xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022 - Modifié le 29 mai 2017 à 18:51
xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022 - 1 juin 2017 à 00:57
salut a tous ^^
j'ai ecrit un code d'une interface java avec netbeans:quand je clique sur un bouton je veux executer un code, le probleme c'est quand je clique sur ce bouton le code s'execute mais je ne peux pas sortir de la fenetre car tout est bloqué svp aidez moi et merci bcp

package javaapplication6;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 * @author TOSHIBA
 */
public class JavaApplication6 {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path dir = Paths.get("C:\\Users\\TOSHIBA\\Pictures");
            dir.register(watcher, ENTRY_MODIFY);
            System.out.println("Watch Service registered for dir: " + dir.getFileName());
            while (true) {
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();
                    System.out.println(kind.name() + ": " + fileName);
                    if (kind == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java")) {
                        System.out.println("My source file has changed!!!");
                    }
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}
A voir également:

1 réponse

KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
29 mai 2017 à 19:45
Bonjour,

Où est le code de ton interface graphique ?
Quelle techno tu utilises ? AWT, Swing, JavaFX, autre ?

Remarque : on peut simplifier un peu le Watcher, d'une part car le type sera forcément ENTRY_MODIFY puisque le register est configuré ainsi, d'autre part parce qu'on n'a pas besoin de savoir que le contexte est de type Path pour faire le toString() dessus.

import java.nio.file.*;

public class JavaApplication6 {

    public static void main(String[] args) throws Exception {
        // Configure WatchService
        Path path = Paths.get("C:/Users/TOSHIBA/Pictures");
        WatchService service = path.getFileSystem().newWatchService();
        path.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
        System.out.println("Watch Service registered for :" + path);

        // Listen WatchEvent
        WatchKey key;
        do {
            key = service.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                if (event.context().toString().equals("DirectoryWatchDemo.java"))
                    System.out.println("My source file has changed!!!");
            }
        } while (key.reset());
    }
}
0
xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022 1
Modifié le 30 mai 2017 à 02:26
salut ,

merci pour votre reponse voici mon code (swing) :
et est ce que je peux afficher les resultats de ce code sur une fenetre et quand je ferme la fenetre l'execution se termine ???
bonne soirée

package application3;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
 
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
/**
 *


* @author TOSHIBA

*/
public class fenetre extends javax.swing.JFrame {

    /**


* Creates new form fenetre

*/
    public fenetre() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setBackground(new java.awt.Color(153, 0, 0));
        jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\TOSHIBA\\Documents\\NetBeansProjects\\Application3\\fond.png")); // NOI18N

        jButton1.setText("snort");

        jButton2.setText("surveiller");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("quitter");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 527, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(62, 62, 62)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(62, 62, 62)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(65, Short.MAX_VALUE))
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path dir = Paths.get("C:\\Users\\TOSHIBA\\Pictures");
            dir.register(watcher, ENTRY_MODIFY);
             
            System.out.println("Watch Service registered for dir: " + dir.getFileName());
             
            while (true) {
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }
                 
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                     
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();
                     
                    System.out.println(kind.name() + ": " + fileName);
                    
                     
                    if (kind == ENTRY_MODIFY &&
                            fileName.toString().equals("DirectoryWatchDemo.java")) {
                        System.out.println("My source file has changed!!!");
                    }
                }
                 
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
             
        } catch (IOException ex) {
            System.err.println(ex);
        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    /**


* @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(fenetre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(fenetre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(fenetre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(fenetre.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 fenetre().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}

0
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015 > xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022
30 mai 2017 à 12:56
Le problème c'est que tu lances ta boucle while dans l'actionPerformed, donc l'action s'effectue dans l'EDT, et tant qu'elle n'est pas terminée les actions de rafraîchissements ne peuvent pas s'effectuer car elles sont gérées par l'EDT qui est déjà occupé...

Ce qu'il faut c'est exécuter ta boucle while dans un autre thread, par exemple avec un SwingWorker en tâche de fond, c'est également lui qui gérera l'arrêt du traitement lorsque l'application se ferme.

Remarque : faire du Swing avec NetBeans c'est cool car ça fait tes fenêtres automatiquement, mais avec un code tout moche, difficile à aller modifier à la main sans que ça perde NetBeans et certainement pas fait pour comprendre comment ça fonctionne (notamment car une partie du code n'est pas standard).
WindowBuilder sous Eclipse est mieux fait, d'une part le code généré est plus propre, en pur Java, et d'autre part en cas d'ajout de composants dans le code il est capable d'aller de les retrouver dans l'éditeur, ce qui permet d'être plus libre dans le code et de mieux comprendre ce que l'on fait.

Remarque : Swing n'est plus mis à jour, depuis Java 8 la bibliothèque officielle pour faire des interfaces graphiques c'est JavaFX.
0
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015 > xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022
Modifié le 30 mai 2017 à 23:33
Voici le code complet avec le SwingWorker.
J'ai remplacé les System.out.println par un setText dans le label où tu mets ton fond.png, mais comme je n'ai pas cette image je ne sais pas trop ce que ça donne, si tu ne vois pas le texte enlève le setIcon (ligne 35)

Remarque : j'en ai profité pour faire du ménage de tout ce que NetBeans rajoute inutilement pour que le code soit plus propre (je l'ai testé avec WindowBuilder)

package application3;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.file.*;
import java.util.Date;

import javax.swing.GroupLayout.Alignment;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.*;

/**
 * @author TOSHIBA
 */
public class Fenetre extends JFrame {

    private static final long serialVersionUID = 1L;

    private final JButton buttonSnort;
    private final JButton buttonSurveiller;
    private final JButton buttonQuitter;
    private final JLabel labelIcon;

    public Fenetre() {

        labelIcon = new JLabel();
        buttonSnort = new JButton();
        buttonSurveiller = new JButton();
        buttonQuitter = new JButton();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        labelIcon.setBackground(new Color(153, 0, 0));
        labelIcon.setIcon(new ImageIcon("C:/Users/TOSHIBA/Documents/NetBeansProjects/Application3/fond.png"));

        buttonSnort.setText("snort");

        buttonSurveiller.setText("surveiller");
        buttonSurveiller.addActionListener(this::surveillerAction);

        buttonQuitter.setText("quitter");
        buttonQuitter.addActionListener(this::quitterAction);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
                        .addComponent(buttonQuitter, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
                                Short.MAX_VALUE)
                        .addComponent(buttonSurveiller, GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                        .addComponent(buttonSnort, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelIcon, GroupLayout.PREFERRED_SIZE, 527, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(39, 39, 39)
                        .addComponent(buttonSnort, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE)
                        .addGap(62, 62, 62)
                        .addComponent(buttonSurveiller, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
                        .addGap(62, 62, 62)
                        .addComponent(buttonQuitter, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(65, Short.MAX_VALUE))
                .addComponent(labelIcon, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE));

        pack();
    }

    private void surveillerAction(ActionEvent evt) {
        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                try {
                    watchService();
                    labelIcon.setText("Watch Service: Finished");
                } catch (IOException | InterruptedException e) {
                    labelIcon.setText("Watch Service: " + e);
                }
                return null;
            }
        }.execute();
    }

    private void watchService() throws IOException, InterruptedException {
        Path path = Paths.get("C:/Users/TOSHIBA/Pictures");
        WatchService service = path.getFileSystem().newWatchService();
        path.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
        labelIcon.setText("Watch Service: Registered for " + path);
        WatchKey key;
        do {
            key = service.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                if (event.context().toString().equals("DirectoryWatchDemo.java"))
                    labelIcon.setText("Watch Service: File changed at " + new Date());
            }
        } while (key.reset());
    }

    private void quitterAction(ActionEvent evt) {
        dispose();
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        EventQueue.invokeLater(() -> new Fenetre().setVisible(true));
    }
}

NB. Ci-dessous une impression écran de WindowBuilder, c'est tout à fait équivalent à ce que propose NetBeans, à part que le code généré sur Eclipse est bien plus facile à modifier par la suite.

0
xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022 1 > KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024
31 mai 2017 à 01:46
aaa d'accord merci beaucoup beaucoup KX ☺ ☺ ☺
0
xko Messages postés 55 Date d'inscription mardi 15 mars 2016 Statut Membre Dernière intervention 28 juillet 2022 1
31 mai 2017 à 15:35
salut quand j'ai lancé ce code il ne me donne pas si un nouveau fichier est arrivé ou un fichier est modifié :'(
0