2014-09-04 35 views
0

我的程序顯示一個UI並根據用戶給定的輸入更新一個JLabel關閉構造函數JAVA的先前實例

我的代碼: -

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

} 
} 

取景器類: -

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; 
} 
} 

問題: -

在執行過程中,在創建UI,我給了輸入和所有的方法被調用和執行和JLabel首次更改。

但是,當我第二次輸入並單擊搜索按鈕時,Jlabel的文本保持不變。

查找器構造函數根據給定的輸入創建元數據,所以如果用戶多次輸入輸入,將會啓動構造函數的多個實例。

現在我做了一些調試,發現第二次時,前面的構造函數的元數據和新的元數據一起還在內存中。

因此第二次輸出mm.find("title");是我們第一次得到的輸出。

請幫我解決這個問題,並提前致謝。

回答

2

static String metadata

你的元數據成員是靜態的,這就是爲什麼該類的所有實例查看並更新該成員的同一副本的原因。

您的構造函數finder附加到靜態成員 - metadata+=s.nextLine()+"\n";。因此,以前的構造函數調用附加的數據仍然存在。

如果您希望finder的每個實例具有不同的metadata,請刪除static關鍵字。

+0

真的很簡單。它的工作,謝謝。 – Mohit 2014-09-04 09:51:03