我正在尝试从文本文件中填充GUI(包括下面的图片)。文本文件有12行文本,如下所示: Matthew Smith;澳大利亚; 60,62,58,62,63,70; 50,52,56,57,60,56。目的是让名称填充jlist,因此当您选择名称时,该国家/地区将显示为' country'旁边的jlabel。并且文本字段将填入分数。我一直在尝试一些事情,但我得到的只是每次在jList中的java.Lang等。有人可以指出我正确的方向吗?非常感谢
private static Scanner inGui;
public Stage3() {
initialize();
}
private void readFile() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("Stage3Scores.txt"));
String line = "";
int iScore = 0;
while((line = reader.readLine()) != null) {
String[] splitLine = line.split(";");
athletes[iScore] = splitLine[0];
countries[iScore] = splitLine[1];
scores[iScore] = splitLine[2];
iScore++;
}
reader.close();
lblDisplayCountry = new JLabel("l");
lblDisplayCountry.setBounds(101, 119, 186, 24);
frame.getContentPane().add(lblDisplayCountry);
listAthlete = new JList();
listAthlete.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
//listAthlete.setText(athletes[listAthlete.getSelectedIndex()]);
lblDisplayCountry.setText(athletes[listAthlete.getSelectedIndex()]);
}
});
listAthlete.setBounds(101, 187, 186, 205);
frame.getContentPane().add(listAthlete);
JButton btnLoadAthlete = new JButton("Load");
btnLoadAthlete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultListModel DLM = new DefaultListModel();
DLM.addElement(""+ athletes +"");
DLM.addElement(""+ countries +"");
DLM.addElement("" + scores + "");
listAthlete.setModel (DLM);
}
});
btnLoadAthlete.setBounds(142, 422, 89, 23);
frame.getContentPane().add(btnLoadAthlete);
}
}
答案 0 :(得分:1)
DefaultListModel是:public class DefaultListModel<E> extends AbstractListModel<E>
所以您可以创建一个类似POJO的类,并覆盖toString方法以显示Athlete Name并将对象添加到DefaultListModel,否则只创建DLM,如下所示:
DefaultListModel<String> DLM = new DefaultListModel<String>();
for(int i = 0; i < athletes.length; i++)
DLM.addElement(athletes[i]);
listAthlete.setModel (DLM);
然后在选择运动员名称时,您可以从相应阵列中获取详细信息,并选择列表项目的索引号。