2014-04-17 156 views
0

我有两个JTextField S和JButton,一个文本框保存到“重点”,另一个保存到“值”保存用户输入的值是在HashMap中使用

我如何得到它从JTextField保存此数据并添加到密钥和值。

另外,如何获取HashMap的“值”并将其添加到JList

谢谢,这一直困扰着我,我发现的一切都是关于HashMap s是您在代码中输入的字符串,不允许用户这样做。

编辑 这是我在JButton的动作进行部分:(我用在NetBeans设计师)

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

(capitalText和countryText是什么我的两个JTextField的名称)

这是我前面的这个代码:

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

老实说,我只是把迪菲租的事情,我在网上找到,并试图把它结合起来,使一些工作,并已成功

+0

JTextFields有获取当前文本的方法。在那里,您可以使用您在文章中提到的文字。如果您已经尝试解决此问题,请在此处发布您的代码。 – csmckelvey

+0

我在上面添加了一个编辑来显示我有什么,有什么方法可以做到这一点?只是我可以谷歌来帮助我得到一个想法,我不希望任何人为我做这件事,我只是在寻找丢失的东西 – user3543727

+0

这里是JTextField [Here](http ://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html) – csmckelvey

回答

0

是的,你可以通过使用此代码把值从两个JTextField S到HashMapLM

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. 

你可以用它来获取从HashMap值。

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

我认为这一定会帮助你。

+0

谢谢你,看起来正是我所需要的!只是现在有搜索问题:( – user3543727

+0

投票。请问一个新的问题。如果你有更多的问题 – ShihabSoft