简体   繁体   中英

Add items to jList

I am trying to create a method that will update a list that has already been created. Im not sure why this is not working?

It throws a null pointer exception.

This is my code:

private void UpdateJList(){
    String query = "SELECT * FROM names WHERE TYA=?";
    String partialSearch = "Sales";
    try{
        connect.pst = connect.con.prepareStatement(query);
        connect.pst.setString(1, partialSearch);
        connect.pst.execute();
        ArrayList<String> add = new ArrayList<String>();
        String[] items = {};
        while (connect.rs.next()){
            String result = connect.rs.getString("ACNO");
            add.add(result);
            int length = add.size();
            DefaultListModel<String> model;
            model = new DefaultListModel<String>();
            for (int i=0; i<length; i++){
                model.add(i, result);
            }
            jList1.setModel(model);     
            jList1.setSelectedIndex(0);
       }
   }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
   }
} 

Thank you in advance!!

There are 2 major problems with that code:

  1. In the while loop, you are creating many instances of DefaultListModel. That means, for each entry of the query result, you are restarting the list.
  2. A nullpointer exception is produced by the line: connect.rs.next() because you didn't assign connect.rs with the query's resultset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM