简体   繁体   English

将项目添加到jList

[英]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. 在while循环中,您将创建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. 该行会产生一个nullpointer异常: connect.rs.next()因为您没有为connect.rs分配查询的结果集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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