Search code examples
javaswinguser-interfacejtextfieldjlist

populate jList and text fields from a .txt file


I am trying to populate a GUI (included pic below) from a text file. The text file has 12 lines of text and is written like this : Matthew Smith;Australia;60,62,58,62,63,70;50,52,56,57,60,56. The aim is to have the names populate the jlist so when you select the name, the country will appear as a jlabel next to 'country' and the textfields will populate with the scores. I've been trying a few things but all I get is the java.Lang etc every time in the jList.. Can someone please point me in the right direction? Thanks very much

pic of GUI

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);

    }
    }

Solution

  • The DefaultListModel is: public class DefaultListModel<E> extends AbstractListModel<E> so what you can do is either create a class like POJO and override toString method to show the Athlete Name and add the object to DefaultListModel otherwise only create the DLM as follows:

    DefaultListModel<String> DLM = new DefaultListModel<String>();
    for(int i = 0; i < athletes.length; i++)
      DLM.addElement(athletes[i]);
    listAthlete.setModel (DLM);
    

    Then on selection of the athlete name you can get the details from appropriate array with the index no of the list item selected.