You shouldn't have to re-read the entire text file again in order to complete the setup of the GUI. I would just read the text file once, then use the Map<String, ArrayList<String>> sections = new HashMap<>();
object to complete the setup of the GUI.
This could be the process for you:
1) Read the entire file and return the sections HashMap.
2) Setup the jPanel2
by adding the SubPanels
to it (e.g. based on the number of Authors).
3) Setup the JComboBox's
by adding the data stored in the HashMap
(e.g. the mapped ArrayList's
).
For number 1), I would just create a method that reads the file and returns the HashMap
.
Read The File
Example (Adapted from your other question here):
public Map<String, ArrayList<String>> getSections ()
{
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);
}
// don't add empty strings
if (v.length() > 0)
{
authors.add(v);
}
lastKey = k;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return sections;
}
GUI Setup
Note: This code can be put wherever you are setting up the GUI now, I'm just placing all in the method below for an example.
public void setupGUI ()
{
// read the file and get the map
Map<String, ArrayList<String>> sections = getSections();
// get the authors
ArrayList<String> authors = sections.get("AUTHOR");
// Setup the jPanel2 by adding the SubPanels
int num = authors.size();
jButton1.addActionListener(new Clicker(num));
jButton1.doClick();
// Setup the JComboBox's by adding the data stored in the map
for (int i = 0; i < authors.size(); i++)
{
int index = i;
// not sure if getComponent() is zero or 1-baed so adjust the index accordingly.
SubPanel panel = (SubPanel) jPanel2.getComponent(index);
// Not sure if you already have the JComboBox in the SubPanel
// If not, you can add them here.
JComboBox jcb = panel.getJcb();
jcb.setSelectedItem(authors.get(i));
}
}
Side Note: I'm not sure why you are creating 12 separate SubPanel's, each with its own JComboBox? Maybe you want to consider how you can better layout the GUI. Just a consideration. In either case, you can use the above examples are a starting point.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…