【发布时间】:2016-05-22 14:14:22
【问题描述】:
我正在将文本文件内容加载到 GUI 并使用此代码计算 HashMap 值:
Map<String, ArrayList<String>> sections = new HashMap<>();
Map<String, String> sections2 = 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) {
}
// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();
// to count HashMap value
jButton1.addActionListener(new Clicker(numOfAuthors));
jButton1.doClick();
// convert the list to a string to load it in a GUI
String authors = "";
for (String a : sections.get("AUTHOR"))
{
authors += a;
}
jcb1.setSelectedItem(authors);
jButton1 的ActionListener 是从here 借来的。
现在我要分配AUTHOR(HashMap 中的项目数为12,所以jButton1 将添加动态12jComboBoxes)值动态创建jComboBoxes。
我试过这段代码:
BufferedReader br = new BufferedReader(new FileReader ("input.txt"));
String str=null;
int i = 0;
while( (str = br.readLine()) !=null ) {
String v = str.substring(12, str.length() - 61).trim();
if(i == 0) {
jcb1.setSelectedItem(v);
} else {
SubPanel panel = (SubPanel) jPanel2.getComponent(i - 1);
JComboBox jcb = panel.getJcb();
jcb.setSelectedItem(v);
}
i++;
}
但这段代码从 input.txt 读取所有行(70 行),但我只想从 @ 分配 12 值987654333@ 字段并在jcb 上显示。
我该如何解决?
【问题讨论】:
-
抱歉,您还想做什么?请澄清,请发布您的minimal reproducible example 或尽可能多的 mcve。
-
对于您的问题、您的代码和您的问题,我仍然非常不清楚,但希望迈克尔的回答是您所需要的。看来他以前帮助过你,所以比大多数人更了解你的设置。不过,如果您可以在这个问题上投入更多精力,那么对未来的访问者来说会更好。另附注:从不有此代码:
catch (IOException e) { }。这不仅仅是糟糕的代码,它是彻头彻尾的危险代码。