Question

I have two JTextField s and a JButton, one textfield saves to "key" and the other saves to "value"

How do I get it to save this data from the JTextField and add to the key and value.

Also, How do I take the "value" of the HashMap and add that to a JList?

Thank you, this has been troubling me, everything I find about HashMap s is strings you enter in the code, not allowing the user to do so.

EDIT This is what I have in the jbutton action performed section: ( I'm using designer in netbeans )

lm.addElement(capitalText.getText());
lm.addElement(countryText.getText());

(capitalText and countryText are what my two jtextfields are name )

This is the code I have preceding this:

private String country;
private String capital;
private DefaultListModel<String> lm = new DefaultListModel<>();
Map<String, String> hashMap = new HashMap<>();
String key = country;
String value = capital;

Honestly I've just took different things I found online and tried to combine it to make something work and have been unsuccessful

Was it helpful?

Solution

Yes you can put the value from two JTextField s to the HashMap lm by using this code.

String key=keyTextField.getText();//This will retrieve the value of JTextField keyTextField and store it to the String variable key.
String value=valueTextField.getText();
hashMap.put(key,value);//This will store the value variable with identifier variable key into the HashMap hashMap.

You can use this to get the value from the HashMap.

String value=hashMap.get(key);//It retrieves the value from hashMap with specific identifier key and stores it the String variable key.

I think this will surely help you out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top