简体   繁体   中英

Add multiple elements to JList

I need to save on a jList multiple values coming from a specific source.

Inside the for cycle i generate both a jComboBox and bot a Model for a Jlist declared above in code (so not visible in this piece of code) What i don't understand, maybe it's a simple problem, is why the jComboBox has all elements taken from the array channelId instead Jlist saves only the last element.

DefaultListModel jList1Model;
private void printChannelData(Channel channel, String nodeName) {   
    String[] channelId = { channel.getId()+" - "+nodeName/*+" - "+channel.getName()*/};
    jList1Model = new DefaultListModel();

    for (int i=0; i < channelId.length; i++) {
        //Adds element to the Single Channel Loading ComboBox
        channelIdComboBox.addItem(channelId[i]);
        //Adds elements to the Multiple Channel Loading ComboBox
        jList1Model.addElement(channelId[i]); 

    }
    jList1.setModel(jList1Model);   
}   

You recreate the ListModel every time you call printChannelData() (probably in a loop somewhere). Create the ListModel outside, and inside the method just add to the model.

And channelId is a String[] , but only contains one item. I don't know what you were trying to do with it.

DefaultListModel<String> jList1Model = new DefaultListModel<>();

// probably a loop where you call printChannelData()
List<ChannelData> channels = ...;
for (ChannelData cd : channels) {
    printChannelData(cd, "whatever");
}


private void printChannelData(Channel channel, String nodeName) {   
    String channelId = channel.getId() + " - " + nodeName + " - " + channel.getName();
    for (int i=0; i < channelId.length; i++) {
        //Adds element to the Single Channel Loading ComboBox
        channelIdComboBox.addItem(channelId[i]);
        //Adds elements to the Multiple Channel Loading ComboBox
        jList1Model.addElement(channelId[i]); 
    }
    jList1.setModel(jList1Model);   
} 

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