Java:将TextField保存到另一个类中使用的字符串中


public  void actionPerformed(ActionEvent e) {
    s = tf1[0].getText();
}

我想保存从tf1[0].getText();String s的文本输入,并在我的main或另一个类中调用s,但我得到了null。有没有办法在另一个班上调用s

这是代码的其余部分:

public class GUI {
static String s;
public static void  gui(){
    {   
        try{
        String File_Name="C:/Users/Ray/Desktop/test.txt";
        ReadFile rf=new ReadFile(File_Name);
        JFrame f1=new JFrame("Maintest");
        JPanel p1=new JPanel();
        JPanel p2=new JPanel();
        final String[] aryLines=rf.OpenFile();
        final JTextField tf1[];
        tf1=new JTextField[22];
        JButton []b1=new JButton[6];
        String bNames="OK";
        final JTextField tf2[]=new JTextField[aryLines.length];
        f1.setSize(200,450);

        JLabel l1[]=new JLabel[20];
        for ( int i=0; i < aryLines.length; i++ )
        {
            b1[i]=new JButton(bNames);
            l1[i]=new JLabel("Enter Serial# for "+ aryLines[i]);
            p1.add(l1[i]);p1.add(tf1[i] = new JTextField());p1.add(b1[i]);
        }

            p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));
            f1.add(p1,BorderLayout.WEST);

                b1[0].addActionListener(new ActionListener(){
                private String s2;
                public  void actionPerformed(ActionEvent e) 
                {
                    s=tf1[0].getText();
                    System.out.print(s);
                }

                });
            f1.show();
        }
            catch(Exception e)
            {
                System.out.print(e);
            }
    }
}

}

对此有几个解决方案。您可以使"s"成为一个基于类的变量,可以从对象实例中检索,如下所示:

public String getS(){
   return this.s;
}

这里:

public  void actionPerformed(ActionEvent e) {
   this.s = tf1[0].getText();
}

然后,在另一个需要s的类中,应该实例化包含s的类并调用:

String s2 = instantiatedObject.getS();

如果你觉得有点冒险,你可以让"s"成为一个静态变量,你可以在任何实例化包含"s"的类的地方调用它:

String s2 = instantiatedObject.s;

相关内容