2014-04-18 30 views
0

到HashMap中你如何從兩個JTextField。就拿值並應用一個鍵和一個的HashMap價值?如何添加2個JTextFields將

這是我的,但我認爲有些事情是不工作的權利,因爲我試圖用不同的代碼段來搜索此而已快到了

if (capitalText.getText().equals("")) { 
    capitalText.requestFocusInWindow(); 
} 
else if (countryText.getText().equals("")) { 
    countryText.requestFocusInWindow(); 
} 
else { 
    lm.addElement(capitalText.getText()); 
    capitalText.setText(value); 
    countryText.setText(key); 
    hashMap.put(key, value); 

    // capitalText.getText(); 

    searchButton.setEnabled(true); 
} 

回答

0

它應該是簡單as

String key = keyTextField.getText(); 
String val = valTextField.getText(); 
hashMap.put(key, val); 

如果您稍後在HashMap中找不到值,那麼您可能會搜索錯誤的密鑰?

0

您必須瞭解Java swing或AWT的基礎知識。 爲了得到從JTextField。你一個文本想要使用此

String text=capitalText.getText();//This will retrieve the value of the JTextField capitalText and store the it to the String variable named text. 

爲了設定值。你想用這個JTextField

capitalText.setText("Some text");//This will set the String value "Some text" to the JTextField capitalText. 

作爲你的問題。你可以用它來實現,你在找什麼。

String key=countryText.getText(); 
String value=capitalText.getText(); 
hashMap.put(key,val); 

Iam sure this will help you。祝您有美好的一天。