在Java中,实例化后在另一个类中的println语句未打印出正确的值。

huangapple go评论65阅读模式
英文:

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

问题

package com.mycompany.test;

import java.io.File;
import javax.swing.JFileChooser;

public class test extends javax.swing.JFrame {

    public test() {
        initComponents();
    }

    private void initComponents() {
        // ... (Generated Code)
    }

    private void BrowseABtnMouseClicked(java.awt.event.MouseEvent evt) {
        // ... (Handling code for Browse button click)
    }

    private void OKBtnMouseClicked(java.awt.event.MouseEvent evt) {
        // ... (Handling code for OK button click)
    }

    public static String getAtext(){
        return AFileTextField.getText();
    }

    public static void main(String args[]) {
        // ... (Nimbus look and feel settings)

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new test().setVisible(true);
        });
    }

    private static javax.swing.JTextField AFileTextField;
    private javax.swing.JButton BrowseABtn;
    private javax.swing.JButton OKBtn;
}
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 -> Selected 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"
    }
}
英文:

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"
    
    
                }
                
    }

答案1

得分: 0

你的问题出在 B类 的这一行:

test tc = new test();

当你实例化你的 test 类时,它的构造函数会被调用,在构造函数中你调用了 initComponents 方法,该方法会重置 AFileTextField 的值。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月9日 22:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63814049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定