简体   繁体   English

DefaultListModel.addElement()不更新JList

[英]DefaultListModel.addElement() doesn't update JList

I'm using Firebase with my Java project, I've added a listener to query data then add the elements to DefaultListModel but the JList only removes the old items and doesn't show the new data. 我在Java项目中使用Firebase,添加了一个侦听器以查询数据,然后将元素添加到DefaultListModel但是JList仅删除了旧项目,而没有显示新数据。
My JList 我的JList

usersData = new DefaultListModel<>();
JList<String> users = new JList<>(usersData);
users.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
users.setSelectedIndex(0);
users.setVisibleRowCount(5);
JScrollPane fruitListScrollPane = new JScrollPane(users);
add(fruitListScrollPane, BorderLayout.SOUTH);

and my firebase value listener 和我的Firebase值侦听器

firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        // remove all old elements from DefaultListModel
        usersData.removeAllElements();
        // get the data from snapshot
        for (DataSnapshot userSnapshot : snapshot.getChildren()) {
            User user = userSnapshot.getValue(User.class);
            String userInfo = "Username: " + user.getUsername() + " & Password: " + user.getPassword();
            // add the info to the model
            usersData.addElement(userInfo);
            // print the info
            System.out.println(userInfo);
        }
    }

    @Override
    public void onCancelled(FirebaseError error) {
    }
});

is usersData the right scope? usersData是正确的范围吗? I'm thinking it has to do with you updating the information in memory, but not on your UI elements. 我认为这与您更新内存中的信息有关,而不是与UI元素有关。 From the code youve given us, you dont assign or refresh the info in JList, just update the DefaultListModel<>. 根据您提供给我们的代码,您无需分配或刷新JList中的信息,只需更新DefaultListModel <>。 Try that 试试看

The problem is my listner's oonDataChange() runs in a thread so I used this code to do what I needed. 问题是我的列表器的oonDataChange()在线程中运行,因此我使用此代码执行了所需的操作。 I send the data list to this method then start adding them one by one. 我将数据列表发送到此方法,然后开始一个接一个地添加它们。

public void addElements(final List<String> data) {
    if (SwingUtilities.isEventDispatchThread())
        return;
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            for (String item : data) {
                usersData.addElement(item);
                System.out.println(item);
            }
        }
    });
}

thanks to Refreshing GUI by another thread in java (swing) 多亏了Java中的另一个线程刷新GUI(摆动)

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

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