0

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?

  • 4
    You are creating a new text field each time in the setter. Make this a field and create it in the constructor... You are also creating a new "income" in the listener. This won't work either. – BretC May 29 '19 at 09:13
  • 1
    This question indicates you are quite new to programming. If that is the case then I'd strongly recommend doing a few command line bases tutorials to get a better grasp of the basics such as where to create and use instances of objects. Otherwise you're in for a lot of pitfalls and trouble with UI development. – Thomas May 29 '19 at 09:26
  • 1
    If your happy with the solution you found, add it as an answer and accept it, instead of editing your question. *That* would help others. – Matthieu May 29 '19 at 20:40
  • 1
    @Matthieu Got it , thank you . will just need a day before i can accept it as an answer. :) –  May 30 '19 at 02:06
  • 1
    Thanks! You can also edit out that part from your question to be complete :) – Matthieu May 30 '19 at 05:08

2 Answers2

1

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 :)

0

You're creating a new object on each call to setIncomeValue(), so you're getting null each time.

Add a JTextField member next to your JButton save and keep the reference to the first setIncomeValue():

JButton save = ...;
JTextField income = setIncomeValue(); // Created once
...

class SaveListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        String test = income.getText();
        ...
    }
}

That will work because SaveListener is an inner class of class Income (please use capitals for class names), and therefore has access to its mother class' members.

Matthieu
  • 2,736
  • 4
  • 57
  • 87