this et objet courant (java)
Répondre à la discussion
Affichage des résultats 1 à 9 sur 9

this et objet courant (java)



  1. #1
    221

    this et objet courant (java)


    ------

    Bonjour

    je debute en java et jaimerais savoir a quoi renvoie le "this" dans cette expression, en d autre termes quel est l'objet courant ? ( le contexte est la gestion de l'evenement clique pour reduire une frame )


    Code:
    private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {                                     
     
            this.setState(JFrame.ICONIFIED);
     
        }
    merci

    -----

  2. #2
    pm42

    Re : this et objet courant (java)

    Dans le cas présent, this référence l'objet de la classe dans laquelle cette méthode est définie, ou d'une de ses sous-classes.
    Pour savoir quel est l'objet courant, il faut plus de code que ce que tu as posté.

    On peut également ne pas écrire ce this.

  3. #3
    221

    Re : this et objet courant (java)

    merci pm42 pour ta reponse ,

    la methode est definie dans la classe loginForm qui gere la frame en question

    dans ce cas c'est l'objet loginForm ?

    le code complet de la classe

    Code:
    public class loginForm extends javax.swing.JFrame {
    
        /**
         * Creates new form loginForm
         */
        public loginForm() {
            initComponents();
            
            //centrer  la fenetre 
            this.setLocationRelativeTo(null);
            
            
            
        }
    
        /**
         * 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() {
    
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jPanel2 = new javax.swing.JPanel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setUndecorated(true);
    
            jPanel1.setBackground(new java.awt.Color(46, 204, 113));
    
            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            jLabel1.setForeground(new java.awt.Color(255, 255, 255));
            jLabel1.setText("X");
    
            jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            jLabel2.setForeground(new java.awt.Color(255, 255, 255));
            jLabel2.setText("-");
            jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jLabel2MouseClicked(evt);
                }
            });
    
            jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            jLabel3.setForeground(new java.awt.Color(255, 255, 255));
            jLabel3.setText("Login Form");
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel1)
                    .addGap(22, 22, 22))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addContainerGap(75, Short.MAX_VALUE))
            );
    
            jPanel2.setBackground(new java.awt.Color(44, 62, 80));
            jPanel2.setMinimumSize(new java.awt.Dimension(497, 260));
            jPanel2.setPreferredSize(new java.awt.Dimension(497, 260));
    
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 500, Short.MAX_VALUE)
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 260, Short.MAX_VALUE)
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, 0)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
    
            pack();
        }// </editor-fold>                        
    
        
        //bouton reduction fentre 
        
        private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {                                     
            
            this.setState(JFrame.ICONIFIED);
                  
        }                                    
    
        /**
         * @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(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(loginForm.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 loginForm().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        // End of variables declaration                   
    }

  4. #4
    pm42

    Re : this et objet courant (java)

    Oui, si tu fais un lf = new loginForm(), this sera égal à lf.

    Si tu fais une class MyLoginForm entends loginForm
    et un mlf = new MyLoginForm(), this sera égal à mlf.

    Mais comme je le disais, this est optionnel en Java et la norme la plus fréquente est de ne pas le mettre sauf quand c'est nécessaire. Certains le mettent systématiquement ceci dit.

  5. A voir en vidéo sur Futura
  6. #5
    221

    Re : this et objet courant (java)

    ok et donc la en l'occurrence on a instancié un objet loginForm, meme si on l'a pas referencé avec une variable contrairement a ton exemple , le this le pointe quand meme ?

    Code:
    /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new loginForm().setVisible(true);
                }
            });

  7. #6
    pm42

    Re : this et objet courant (java)

    Oui. Je l'ai juste référencé pour te donner un exemple.

  8. #7
    Ikhar84
    Animateur Informatique

    Re : this et objet courant (java)

    Sans vouloir court-circuiter pm, this est en général implicite, on l'utilise explicitement quand, par exemple, on a une méthode de classe qui a besoin d'appeler un méthode d'une autre classe qui a l'objet en paramètre.

    Pas très clair, je sais...

    Typiquement en développement en "couches", la couche de présentation "manipule" des objets métiers, et c'est ces objets qui sont chargés de leur persistance, pas la couche de présentation, on aurun truc du genre (langage fictif, basé plutôt sur C# que Java):
    Code:
    Classe Client{
        int Id;
        string nom;
        Etc...
    
         internal Client (.....) {}
    
         internal int StockerBDD() {
              DataAccess da = new DataAccess();
              return da.Stocker(this);
        }
    }
    Avec ce code fictif, la classe Client fait appel a la classe DataAccess pour stocker en base de données un nouveau client, et retourne la clé primaire de cette occurence.

    Pour pouvoir passer en paramètre de la méthode Stocker de la classe d'accès aux données, on utilise explicitement le mot clé this.

    Le code présenté est volontairement concis et pas très clean pour se concentrer sur l'utilisation de mot clé ! Pas le temps (ni l'envie) de faire un vrai code qui compile, surtout en Java là...

    En dehors de ces cas explicite, pas besoin donc de l'utiliser, mais ça peut rendre un code clair d'après certains, chacun à ses "tiques" de codage
    J'ai glissé Chef !

  9. #8
    pm42

    Re : this et objet courant (java)

    Citation Envoyé par Ikhar84 Voir le message
    Sans vouloir court-circuiter pm,
    Pas du tout, tu précises ce que j'ai eu la flemme de faire. C'est super.

  10. #9
    Ikhar84
    Animateur Informatique

    Re : this et objet courant (java)

    Oui j'avais compris, mes fautes de frappes montrent aussi ma flem... euh fatigue... mais je voulais t'épargner un long exemple en Java !
    J'ai glissé Chef !

Discussions similaires

  1. Peut-on confondre objet du modèle et objet réel ?
    Par Dattier dans le forum Discussions scientifiques
    Réponses: 30
    Dernier message: 08/06/2017, 14h28
  2. Abaqus, appliquer un effort sur un objet, entrainant un objet, qui en entraine lui-même un 3eme.
    Par Benji23245 dans le forum Logiciel - Software - Open Source
    Réponses: 4
    Dernier message: 04/07/2016, 10h22
  3. Problème d'objet dans Java !
    Par Cotton dans le forum Programmation et langages, Algorithmique
    Réponses: 2
    Dernier message: 09/11/2015, 12h02
  4. Créer un courant qui repousse au contact tout objet chargé ?
    Par invitec59563ee dans le forum Technologies
    Réponses: 10
    Dernier message: 19/02/2011, 14h14
  5. Java, java, java, where are you, there's a mission for you !
    Par invite1237a629 dans le forum Logiciel - Software - Open Source
    Réponses: 35
    Dernier message: 16/03/2008, 22h10