Using the code from this link loading text file contents to GUI:
Map> 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 authors = null;
if(sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList();
sections.put(k, authors);
}
authors.add(v);
lastKey = k;
}
} catch (IOException e) {
}
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();
Now I w'd like to use numOfAuthors as a parameter of jButton1, for example:
jButton1.doClick(numOfAuthors);
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();
}
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
But for this moment jButton1 adds just 1 sub.
I can't understand why it doesn't work properly.
解决方案
Write a class which implements 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);
}
}
You would then register this ActionListener against your JButton
jButton1.addActionListener(new Clicker(12));
Remember, if you've previously added any ActionListeners 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