简体   繁体   English

Java-加载Jframe后如何更新JList

[英]Java - How to update JList once Jframe has been loaded

        Connection connection = newConnection.createConnection();
        Statement newStat = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet res = newStat.executeQuery("SELECT contactName FROM Contact WHERE accountName='"+m+"'");
        Vector<String> temp = new Vector<String>();
        //res.first();
        while (res.next()){
            temp.add(res.getString("contactName"));
        }
        newStat.close();
        connection.close();
        customerContactList = new JList(temp);
        repaint();

I have a Jlist with account names, when an account is selected, on the side there is a button which has to be pressed for in order to call the code above. 我有一个带有帐户名称的Jlist,选择一个帐户时,在侧面有一个按钮必须按下才能调用上面的代码。 The code is supposed to get contact names associated to that account and populate them into the JList. 该代码应获取与该帐户关联的联系人姓名,并将其填充到JList中。 This does not happen. 这不会发生。 The Jlist stays blank, i debugged and the vector temp does get 3 values and stores them into the new jlist, the problem is, JList does not refresh. Jlist保持空白,我进行了调试,向量temp确实获得了3个值,并将它们存储到新的jlist中,问题是JList不刷新。

How can I make it refresh? 如何使它刷新?

Thanks a lot and I appreciate any help. 非常感谢,感谢您的帮助。 Kunal 库纳尔

您创建的新JList尚未添加到任何容器中,因此您必须像原始容器一样将其添加到框架中,然后在框架上调用“ validate()”(添加时总是必要的) /将组件移到可见的窗口。)但是最好在现有JList上调用setListData()-它会立即更新,而闪烁的次数较少。

You can use a ListModel to manipulate the data inside the JList . 您可以使用ListModel来操纵JList的数据。 And definitely not create new JLists at any step. 绝对不要在任何步骤创建新的JLists

You have your JList bounded to your JFrame . 您的JList绑定到JFrame Now you can get the data inside it using 现在,您可以使用来获取其中的数据

    JList list = new JList();
    ListModel model = list.getModel();

and modify that model, then send the new model back: 并修改该模型,然后将新模型发回:

    DefaultListModel listModel = new DefaultListModel();
    while (res.next()) {
        listModel.addElement( res.getString("contactName") );
    }
    list.setModel(listModel);

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

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