Reputation: 1063
My program displays an UI and updates a JLabel according to the user given input.
My Code:-
public static void main(String[] args)
{
createUI();
}
public void createUI()
{
// creates the UI using JSwing
// takes userinput from textfield and stores it in variable:- path.
// The UI is updated on the click of button.
JButton bu = new JButton("Search");
bu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
finder mm= new finder(path);
String namefomovie = mm.find("Title");
//nameb is a Jlabel in the UI
nameb.setText(namefomovie);
}
}
finder class:-
public class finder
{
static String metadata="";
public finder(String path) throws FileNotFoundException
{
File myfile = new File(path);
Scanner s = new Scanner(myfile);
while(s.hasNextLine())
metadata+=s.nextLine()+"\n";
}
public String find(String info)
{
//finds the required info stored in metadata and return the answer.
return ans;
}
}
Problem:-
During execution, the UI is created and I give the input and all the methods are called and performed and the JLabel is changed the first time.
But when I give input second time and click on search button, the Jlabel's text remains same.
finder constructor creates a metadata according to the given input, so if a user is giving input multiple time, multiple instances of the constructor is going to be initiated.
Now I did some debugging and found that during the second time, the previous constructor's metadata is still in the memory along with the new metadata.
So the output of the mm.find("title");
the second time is the same output we got the first time.
Please help me fix this and thanks in advance.
Upvotes: 0
Views: 64
Reputation: 393781
static String metadata
Your metadata member is static, which is the reason why all instances of that class see and update the same copy of that member.
Your constructor of finder
appends to the static member - metadata+=s.nextLine()+"\n";
. Therefore the data appended by previous constructor calls is still there.
If you wish each instance of finder
to have different metadata
, remove the static
keyword.
Upvotes: 2