Hello,

I have a JList which contains all data from mySQL table. I want the user to be able to select an item from the list and show it on the label.

When I click on the first item it works, However when I click on the other items, the label is blank. Can anyone help me.

   public void populateList(){
               Connection con = null;
    ResultSet rs = null;
   PreparedStatement st = null;
   Properties conProps = new Properties();
          conProps.setProperty("user", "root");
        conProps.setProperty("password", "root");

       try {
                  con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/root", conProps);

              con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE );
             con.setAutoCommit(false);
            st = con.prepareStatement("SELECT * FROM Students");
            st.executeQuery();
            rs = st.getResultSet();

            int i = 0;
            DefaultListModel info = new DefaultListModel();

               while (rs.next()) {
 final String[] data;
                   data = new String[100];
                   data [i] = (rs.getString("Name") + ", " + rs.getString("Surname")) ;
                   jList2.setModel(info);
                   info.addElement(data[i]);
                   i = i+1;

                   jList2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

                   jList2.setVisibleRowCount(100);

                   jList2.addListSelectionListener(new ListSelectionListener(){

                       public void valueChanged(ListSelectionEvent event){
                          //what to do when item is selected

                           lb1.setText(data[jList2.getSelectedIndex()]);

                       }} );



               }

       }catch(Exception e){
           System.out.print(e);

       }


   }

Recommended Answers

All 3 Replies

Anyone?

Line 23 you create a new data array every time you go through the loop, thus loosing the data from every earlier pass. You probably want to just create one data array, before you enter the loop.

Thank you so much it works now!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.