【问题标题】:Save user inputted values from jtextfield to a string that is used in hashmap将用户输入的值从 jtextfield 保存到 hashmap 中使用的字符串
【发布时间】:2014-06-02 04:23:54
【问题描述】:

我有两个JTextField 和一个JButton,一个文本字段保存到“key”,另一个保存到“value”

如何获取它来保存来自JTextField 的数据并添加到键和值。

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

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

编辑 这是我在执行的 jbutton 操作部分中的内容:(我在 netbeans 中使用设计器)

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

(capitalText 和 countryText 是我的两个 jtextfields 的名称)

这是我之前的代码:

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

老实说,我只是拿了我在网上找到的不同的东西,并试图将它们组合起来,但没有成功

【问题讨论】:

  • JTextFields 具有获取其中当前文本的方法。从那里您可以使用您在帖子中提到的文本。如果您已经尝试过任何方法来解决此问题,请在此处发布您的代码。
  • 我在上面添加了一个编辑来显示我所拥有的,什么方法允许这样做?只是我可以谷歌帮助我得到一个想法,我不希望有人为我做这件事,我只是不知道要搜索什么
  • 这里是 JTextField Here的文档

标签: java hashmap jbutton jtextfield jlist


【解决方案1】:

是的,您可以使用此代码将两个 JTextField 的值放入 HashMap lm

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.

我想这肯定会对你有所帮助。

【讨论】:

  • 谢谢你,这正是我所需要的!!只是现在搜索有问题:(
  • 投票。问一个新问题。如果你有更多问题
猜你喜欢
  • 2014-11-26
  • 1970-01-01
  • 2022-11-02
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2017-09-03
相关资源
最近更新 更多