Reputation:
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?
Upvotes: 0
Views: 54
Reputation:
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 :)
Upvotes: 1
Reputation: 3098
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.
Upvotes: 0