使用此 link 中的代码将文本文件内容加载到 GUI:
Map<String, ArrayList<String>> sections = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
ArrayList<String> authors = null;
if(sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList<String>();
sections.put(k, authors);
}
authors.add(v);
lastKey = k;
}
} catch (IOException e) {
}
在 @Michael Markidis 的帮助下,使用此代码对 HashMap
项进行计数:
// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();
现在我想使用 numOfAuthors
作为 jButton1
的参数,例如:
jButton1.doClick(numOfAuthors);
实际上 GUI 的一般结构:我有 jPanel1
和 jTextField1
和 jButton1
。 jButton1
将动态 tf
添加到 jPanel2
。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SubPanel sub = new SubPanel();
jPanel2.add(sub);
jPanel2.revalidate();
}
HashMap
中的项数是 12
,所以我想使用这个数字作为 的参数jButton1
并点击 12
次并添加额外的 12
sub
' s。
System.out.println(numOfAuthors);
Output: 12
但此时 jButton1
仅添加 1
sub
。
我不明白为什么它不能正常工作。
最佳答案
编写一个实现ActionListener
的类
public class Clicker implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
}
}
向此类添加一个带有数字的构造函数
public class Clicker implements ActionListener {
private int count;
public Clicker(int count) {
this.count = count;
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
例如,使用它来确定您需要做什么
@Override
public void actionPerformed(ActionEvent e) {
for (int index = 0; index < count; index++) {
SubPanel sub = new SubPanel();
jPanel2.add(sub);
}
}
然后,您将针对您的 JButton
注册此 ActionListener
jButton1.addActionListener(new Clicker(12));
请记住,如果您之前向按钮添加了任何 ActionListener
,您需要先将其删除
看看How to Use Buttons, Check Boxes, and Radio Buttons和 How to Write an Action Listeners了解更多详情
对于稍微更高级的方法,您可以考虑查看 How to Use Actions
关于java - jButton HashMap 计数点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317634/