Search code examples
javastringgettextactionevent

Java: Saving TextField to a string used in another class


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

I want to save the text input i get from tf1[0].getText(); to String s and call s in my main , or in another class, but I get null back instead. Is there a way to call s in another class?

this is the rest of the code:

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);
            }

    }
}


}

Solution

  • There are a couple solutions to this. You can make "s" a class based variable that can be retrieved from the object instance like this:

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

    And here:

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

    Then in your other class needing s, you should instantiate the Class containing s and call:

    String s2 = instantiatedObject.getS();
    

    If you feel getting a little risky, you can make "s" a static variable and you can just call it anywhere you instantiate the class containing "s":

    String s2 = instantiatedObject.s;