Search code examples
javaswingjtextfield

Accessing JTextField Text


I have a simple program, I am trying to access the data from the textfield but I am always getting null or empty field.

For an example.

public class income {   
JButton save = new JButton("save");

  public JTextField setIncomeValue() {
  ..
  ..
    JTextField incomeValue = new JTextField(10);
    return incomeValue;
  }

  public void launch_Ui{
   frame.add(setIncomeValue());
   frame.add(save);
   save.addactionlistener(new saveListener());
  }
}

class saveListener  implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        String test = new income().setIncomeValue().getText();
        System.out.println("savings...  " + test + " value ?");
    }

}

Anybody have any idea or have stumble upon this challenge before?


Solution

  • Updates

    After looking through my logic carefully, i have finally come out with a solution.
    What i did was to create a scope inside my savelistener .

    class saveListener implements ActionListener{
    
    JTextField incomeData;
    
    public saveListener(JTextField incomeData) {
        this.incomeData = incomeData;
     }
    
     @Override
     public void actionPerformed(ActionEvent e) {
     String test = incomeData.getText();
        System.out.println("Input data " + test);
      }
    }
    

    Hope this will help those who are in need :)