Search code examples
javajtextfield

Java JTextField output from one class to another?


this is a very simple program that I need help with. I'm trying to show the input entered in a JTextField inside of a actionlistener but when I compile the program I get an errors saying "error: cannot find symbol" pointing at this line --String input = field.getText();-- at the second class . I guess its because it doesn't recognize the JTextField name from the first class but how do I get the second class to recognize it? Please help im trying to learn on my own,and yes im a noob sorry and thank you.

ps. All it has to do is show the input in a system.out.println in the second class.

    import java.awt.* ;
    import java.awt.event.* ;
    import java.sql.* ;
    import java.util.* ;
    import javax.swing.* ;
    import javax.swing.border.* ;
    import javax.swing.event.* ;
    import javax.swing.table.* ;

    class Test
    {
        public static void main(String[] args)
       {

         Test gui = new Test() ;

       }

        public Test()
       {
       JPanel panel1 = new JPanel(new BorderLayout(10,10));  
       JTextField field = new JTextField(22);
       field.addActionListener(new FieldInputAction()) ;     

       panel1.add(field ,BorderLayout.NORTH);

       JFrame f = new JFrame();
       f.setTitle("TEST") ;
       f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);  
       f.setSize(1000, 700) ;
       f.setVisible(true) ;  
       f.setContentPane(panel1) ;

       }

       class FieldInputAction implements ActionListener
       {

          public void actionPerformed(ActionEvent e)
          {  
             String input = field.getText();
             System.out.println(input);
          }


       }





    }

Solution

  • The reason is that field is out of scope when you call it. Since it's declared inside of the curly braces (that is, the "block") for Test(), it's therefore only accessible within Test().

    The simplest way to fix this is just to make field an instance variable. So:

    class Test
    {
        private JTextField field; //Add this line
    
        public static void main(String[] args)
        {
        //etc.
        field = new JTextField(22); //Note that we no longer declare it, only initialize it.
        //etc.