Kung Pao
Kung Pao

Reputation: 79

println statement after instantiation in another class in java does not print out the right value

I am using Apache NetBeans 11.2 and class variable does not print out the assigned value. It's a part of JFrame Form. Form has a button with a mouse click event

Description: I am trying to create a simple JFrame Form with a single Button an a OK button in my case which has a mouse clicked event and opens up a file chooser dialog box and you get the file and in return it updates the text field with the selected file path which I am trying to use in class B but as you can see in the first println statement in class B it prints out the file path from the text field that is selected but after calling new() method on Toolstest class, both println statements prints out default value "File Path" and not the selected file path. I did not include Jframe form code.

I hope this makes everything clear. Thanks for your help.

package com.mycompany.test;

import java.io.File;
import javax.swing.JFileChooser;
public class test extends javax.swing.JFrame {

    
    public test() {
        initComponents();
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        BrowseABtn = new javax.swing.JButton();
        OKBtn = new javax.swing.JButton();
        AFileTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        BrowseABtn.setText("jButton1");
        BrowseABtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                BrowseABtnMouseClicked(evt);
            }
        });

        OKBtn.setText("jButton2");
        OKBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                OKBtnMouseClicked(evt);
            }
        });

        AFileTextField.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(157, 157, 157)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(AFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(OKBtn)
                        .addComponent(BrowseABtn)))
                .addContainerGap(172, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(BrowseABtn)
                .addGap(18, 18, 18)
                .addComponent(AFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addComponent(OKBtn)
                .addContainerGap(115, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void BrowseABtnMouseClicked(java.awt.event.MouseEvent evt) {                                        
        // TODO add your handling code here:
        if(evt.getSource() == BrowseABtn){
                        JFileChooser fc = new JFileChooser("");
                        int returnVal = fc.showOpenDialog(BrowseABtn);
                        
                        if(returnVal == JFileChooser.APPROVE_OPTION){
                        File file = fc.getSelectedFile();
                        AFileTextField.setText(file.getPath());
                        AFileTextField.setEditable(false);
                        }
                    }
    }                                       

    private void OKBtnMouseClicked(java.awt.event.MouseEvent evt) {                                   
        // TODO add your handling code here:
        
        if(evt.getSource() == OKBtn){
                new B().SomeFunccall();
            }
    }                                  

    
    public static String getAtext(){
        return AFileTextField.getText();
    }
    
    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(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(() -> {
                new test().setVisible(true);
            });
        }
    
        // Variables declaration - do not modify                     
        private static javax.swing.JTextField AFileTextField;
        private javax.swing.JButton BrowseABtn;
        private javax.swing.JButton OKBtn;
        // End of variables declaration                   
    }
    
                    
                    package com.mycompany.test;
    
    public class B {
        
         public void SomeFunccall() {
    
            System.out.println(test.getAtext()); //Prints out the right value from the Text Field, prints -> Slected File Path
    
            test tc = new test();
    
            System.out.println(tc.getAtext()); //DOES NOT Print out the right value from the Text Field -> Default Value = "File Path"
    
            System.out.println(test.getAtext()); //DOES NOT Print out the right value from the Text Field -> Default Value = "File Path"
    
    
                }
                
    }

Upvotes: 0

Views: 69

Answers (1)

Lev M.
Lev M.

Reputation: 6269

Your problem is this line in class B:

test tc = new test();

When you instantiate your test class, its consructor is called, and in the constructor you call initComponents which resets the value of AFileTextField.

Upvotes: 0

Related Questions