简体   繁体   中英

Java JList doesn't show elements

I have a JList which is supposed to display a list of school tests. When I add values to this list in Swing Designer then it displays everything correctly, but when I try to display my own data it still shows the values initialized in Swing Designer. How to display my own set of data in JList? My initial update in code:

    public void updateFrame(MainFrame mainFrame)
{
    DefaultListModel<Test> listModel = new DefaultListModel<Test>();
    for(int i = 0 ; i < this.getTestList().size() ; i++)
        listModel.add(i, this.getTestList().get(i));
    JList<Test> currList = new JList<>(listModel);      
    currList.setVisible(true);
    mainFrame.setList(currList);
    mainFrame.getList().setVisible(true);
}

Also my ListListener doesn't activate at any moment, but it's another problem, maybe easier to figure out after the first one.

class ListListener implements ListSelectionListener {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        DefaultListModel<Test> listModel = new DefaultListModel<Test>();
        for(Test test : model.getTestList())
            listModel.addElement(test);
        JList<Test> currList = new JList<Test>(listModel);
        mainFrame.setList(currList);
    }
}

Again, don't swap components but rather models, something like:

public void updateFrame(MainFrame mainFrame) {
    DefaultListModel<Test> listModel = new DefaultListModel<Test>();
    for(int i = 0 ; i < this.getTestList().size() ; i++) {
        listModel.add(i, this.getTestList().get(i));
    }

    // ***** get rid of this *****
    // JList<Test> currList = new JList<>(listModel);      
    // currList.setVisible(true);
    // mainFrame.setList(currList);

    // ***** and instead simply do this *****
    mainFrame.getList().setModel(listModel);
}

If this doesn't work, then yes, create and post your MCVE

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