问题描述
使用此链接中的代码将文本文件内容加载到GUI:
Using the code from this link loading text file contents to 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
个项目进行计数:
With the help of @Michael Markidis counting the HashMap
items using this code:
// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();
现在我想使用numOfAuthors
作为jButton1
的参数,例如:
Now I w'd like to use numOfAuthors
as a parameter of jButton1
, for example:
jButton1.doClick(numOfAuthors);
实际上是GUI的一般结构:我有jPanel1
和jTextField1
和jButton1
. jButton1
将动态tf
添加到jPanel2
.
Actually general structure of GUI: I have jPanel1
with jTextField1
and jButton1
. jButton1
adding dynamic tf
to jPanel2
.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SubPanel sub = new SubPanel();
jPanel2.add(sub);
jPanel2.revalidate();
}
HashMap
中的项目数为 12
,因此我想将此数字用作jButton1
的参数,然后单击 12
em>次并添加其他 12
sub
.
The number of items in HashMap
is 12
, so I wo'd like to use this number as a parameter of jButton1
and click 12
times and add additional 12
sub
's.
System.out.println(numOfAuthors);
Output: 12
但目前jButton1
仅添加 1
sub
.
我不明白为什么它不能正常工作.
I can't understand why it doesn't work properly.
推荐答案
编写一个实现ActionListener
public class Clicker implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
}
}
向此类添加数字的构造函数
Add a constructor to this class which takes a number
public class Clicker implements ActionListener {
private int count;
public Clicker(int count) {
this.count = count;
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
例如,使用它来确定所需要做的事情
Use this to make determinations about what you need to do, for example
@Override
public void actionPerformed(ActionEvent e) {
for (int index = 0; index < count; index++) {
SubPanel sub = new SubPanel();
jPanel2.add(sub);
}
}
然后您将在您的JButton
jButton1.addActionListener(new Clicker(12));
请记住,如果您先前已将任何ActionListener
添加到按钮中,则需要先将其删除
Remember, if you've previously added any ActionListener
s to the button, you'll want to remove them first
看看如何使用按钮,复选框和单选按钮按钮和如何为它编写动作监听器更多详情
对于稍微高级的方法,您可以考虑查看如何使用动作
For a slightly more advanced approach, you might consider having a look at How to Use Actions
这篇关于jButton HashMap计数请点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!