在NetBeans IDE 7.1.1中创建一个JFrame窗口程序。其中包含jTextField控件。现在需要在其他类中获取jTextField控件中的数据。
我是通过在JFrame中添加一个public方法,获取jTextField中的值。再到其他类中引用JFrame中的公共方法。结果在其他类中能获取jTextField中的初始值。更改后就不能即时的获取到了。
经测试:
JFrame中的public方法可以实时的获取jTextField中的值,但是经其他类一转,就变味了,这是咋解决啊、
代码如下:public class NewJFrame extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public String getback()//这个就是公共方法 { String c; c = jTextField1.getText(); // System.out.println(c); return c; } public NewJFrame() { 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"> private void initComponents() { jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setText("erg"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jButton1.setText("jButton1"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(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.LEADING) .addGroup(layout.createSequentialGroup() .addGap(156, 156, 156) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addGap(108, 108, 108) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(132, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(63, 63, 63) .addComponent(jButton1) .addContainerGap(145, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { NewClass s = new NewClass();//newclass是新建其他的类,ee是其中的一个方法,只是打印。 s.ee(); // String m = getback(); // System.out.println(m); // TODO add your handling code here: } /** * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JTextField jTextField1; // End of variables declaration } 
/*****************************其他类****************************/ public class NewClass { public void ee(){ NewJFrame j = new NewJFrame(); String k = j.getback(); System.out.println(k); // b = j.getback(); } } 

解决方案 »

  1.   

    发的有点问题。http://topic.csdn.net/u/20120410/00/29ff4ea9-797d-44ca-bf8d-ce5076acc9ac.html
    另外开的帖子。
      

  2.   


    public class A {
    private B b;
    public A(B b) {
    this.b = b;
    }
    //这样的B就随便修改B里的值了
    }
    public class B {}
      

  3.   

    建议把改类的实例传过去,
    在用该实例的getback(),不就行了?
      

  4.   

    持有对象引用??
    才接触java,怎么弄啊。
    什么是持有对象引用??
      

  5.   


    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     *//**
     *
     * @author xxl
     */
    public class NewJFrame extends javax.swing.JFrame {
        private String c;//添加的    /**
         * Creates new form NewJFrame
         */
        public String getback()//添加的
        {
            //String c;
            //c = jTextField1.getText();
           // System.out.println(c);
            return  this.c = jTextField1.getText();//添加的
        }
        public NewJFrame() {
            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">                          
        private void initComponents() {        jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jTextField1.setText("erg");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });        jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(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.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(156, 156, 156)
                            .addComponent(jButton1))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(108, 108, 108)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(132, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(48, 48, 48)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(63, 63, 63)
                    .addComponent(jButton1)
                    .addContainerGap(145, Short.MAX_VALUE))
            );        pack();
        }// </editor-fold>                            private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                               private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            NewClass  s = new NewClass();
            s.ee();
          // String m =  getback();
        //   System.out.println(m);
            // TODO add your handling code here:
        }                                            /**
         * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                   
    }
    //在这里引用上面getback()方法
    public class NewClass {
        public void ee(){
        NewJFrame j = new NewJFrame();
        String k = j.getback();
        System.out.println(k);
       // b = j.getback();
        }
        
    }上面NewClass 中调用getback()还是不成功,当public class NewJFrame里面jTextField1里面新输入的数据还是不能传到NewClass 中。
    求解析。。还有持有对象引用,怎么弄啊。
      

  6.   

        public JTextField getback()
        {
            return  this.jTextField1;
        }
    这是对象引用
      

  7.   


    public class NewJFrame extends javax.swing.JFrame {
        private String c;    public String getback()
        {
            return  this.c = jTextField1.getText();
        }                        
    .......
    .......
    .......
    .......
    .......    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                               private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            NewClass s = new NewClass();
            s.ee();
        }                                        .......
    ......
    .....                   
    }
    public class NewClass {    private NewJFrame j;
        
        public NewClass(NewJFrame j)
        {
    this.j = j;
        }
        public void ee(){
        String k = j.getback();
        System.out.println(k);
        }
        
    }
      

  8.   


    在NewClass中你又New了一个新的NewJFrame类对象跟调用NewClass的那个NewJFrame对象不是一个,当然不能获取最开始的那个NewJFrame对象的JTextField的内容
      

  9.   


     public JTextField getback()
        {
            return  this.jTextField1; }
    //这个不行?    
      

  10.   


    //运行结果出现这个提示
    /*run:
    javax.swing.JTextField[,108,48,160x28,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@5660d6,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=,disabledTextColor=DerivedColor(color=142,143,145 parent=nimbusDisabledText offsets=0.0,0.0,0.0,0 pColor=142,143,145,editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=DerivedColor(color=255,255,255 parent=nimbusSelectedText offsets=0.0,0.0,0.0,0 pColor=255,255,255,selectionColor=DerivedColor(color=57,105,138 parent=nimbusSelectionBackground offsets=0.0,0.0,0.0,0 pColor=57,105,138,columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
    javax.swing.JTextField[,108,48,160x28,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@1a6684f,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=,disabledTextColor=DerivedColor(color=142,143,145 parent=nimbusDisabledText offsets=0.0,0.0,0.0,0 pColor=142,143,145,editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=DerivedColor(color=255,255,255 parent=nimbusSelectedText offsets=0.0,0.0,0.0,0 pColor=255,255,255,selectionColor=DerivedColor(color=57,105,138 parent=nimbusSelectionBackground offsets=0.0,0.0,0.0,0 pColor=57,105,138,columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]*/没有成功的。
      

  11.   

    我试了。还是有问题private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            NewClass  s = new NewClass();//这里提示说在NewClass里面没有构造函数,我自动添加了后。运行//成功了,但是传值的时候报错。大致在两处处,一处是构造函数,其次在jButton1ActionPerformed里面//NewClass  s = new NewClass()这里
            s.ee();
          // String m =  getback();
        //   System.out.println(m);
            // TODO add your handling code here:
        }               
    你这个方法是上面原理呢。
    以前我没有用过呢。
      

  12.   


    额,这样的啊,但是如果不new一个出来,怎么传那边的方法呢?求指点。具体是上面实现的额
      

  13.   

    楼主,我的意思是。
    哎,
    能把你用的那部分代码贴出来吗?
    一个这么简单的引用,你可以用 s.getback().getText();
    你只要把NewClass  s = new NewClass()
    这个 s引用传到你要的那个界面。
      

  14.   

       /*********JFrame 窗体类************/      
    public class NewJFrame extends javax.swing.JFrame 
    {
           /*********这个方法是获取输入框中的值,并返回(需要在其他类中使用)************/   
        public String getback()
        {
            return  this.jTextField1.getText();
        }
       /**********输入框jTextField1***********/                        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           
       /**********确定按钮调用NewClass类中的方法ee()(该方法是打印输入框中的值)***********/ 
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            NewClass  s = new NewClass();
            s.ee();
                     
    }
    }   /**********一个新的类,它先通过getback()方法获取上面输入框中的值,在打印***********/ 
    public class NewClass {
        public void ee(){
        NewJFrame j = new NewJFrame();
        String k = j.getback();
        System.out.println(k);
           }
        
    }问题是:jTextField1值不能及时的传送到Newclass类这边。
    老兄,初学这玩意,标示鸭梨黑大啊。
      

  15.   


    public class NewJFrame extends javax.swing.JFrame {
        private String c;    public String getback()
        {
            return  this.c = jTextField1.getText();
        }                        
    .......
    .......
    .......
    .......
    .......    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                               private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            NewClass s = new NewClass(this);//这里要有参数,不然找不到构造函数
            s.ee();
        }                                        .......
    ......
    .....                   
    }
    public class NewClass {    private NewJFrame j;
        
        public NewClass(NewJFrame j)
        {
        this.j = j;
        }
        public void ee(){
        String k = j.getback();
        System.out.println(k);
        }
        
    }或者这样也行public class NewJFrame extends javax.swing.JFrame {
        private String c;
        private NewClass s = new NewClass(this);//直接作为一个成员变量不用总new了    public String getback()
        {
            return  this.c = jTextField1.getText();
        }                        
    .......
    .......
    .......
    .......
    .......    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                               private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            s.ee();
        }                                        .......
    ......
    .....                   
    }
    public class NewClass {    private NewJFrame j;
        
        public NewClass(NewJFrame j)
        {
        this.j = j;
        }
        public void ee(){
        String k = j.getback();
        System.out.println(k);
        }
        
    }
      

  16.   


    package socket;
    public class NewJFrame extends javax.swing.JFrame {
        
    private javax.swing.JButton jButton1;
        private javax.swing.JTextField jTextField1;
        /**
         * Creates new form NewJFrame
         */
        public javax.swing.JTextField getback()//注释过的改动了。其他无改动
        {
            return this.jTextField1;
        }    public NewJFrame(){
            initComponents();
        }
            private void initComponents() {        jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jTextField1.setText("erg");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });        jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(java.awt.event.ActionEvent evt){
                    jButton1ActionPerformed(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.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(156, 156, 156)
                            .addComponent(jButton1))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(108, 108, 108)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(132, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(48, 48, 48)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(63, 63, 63)
                    .addComponent(jButton1)
                    .addContainerGap(145, Short.MAX_VALUE))
            );        pack();
        }                        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt){
        
        }                                               private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){                                         
            NewClass s = new NewClass(this);
            s.ee();//或者s.ee(this),这种就不写了,一般是上面那种写法。
        }
        
        public static void main(String args[]) {
            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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
    }class NewClass {//如果你的NewClass 就这里用到了,直接写一个文件夹下就可以了。看个人爱好
    private NewJFrame newJFrame = null;
        public NewClass(NewJFrame newJFrame){
         this.newJFrame = newJFrame;
        }
    public void ee(){
        String k = newJFrame.getback().getText();
        System.out.println(k);
        }
    }
      

  17.   

    不胜感激。问题已经解决。
    public class NewClass {
        private NewJFrame j;//不过这里是什么意思呢没搞懂
        public NewClass(NewJFrame j) 
        { 
            this.j = j; 
        }
        public void ee()
        { 
            String k = j.getback(); 
            System.out.println(k); 
        }