简体   繁体   English

将多个元素添加到JList

[英]Add multiple elements to JList

I need to save on a jList multiple values coming from a specific source. 我需要在jList上保存来自特定源的多个值。

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. 在for循环中我生成了一个jComboBox和bot一个Model用于代码中的上面声明的Jlist (因此在这段代码中不可见)我不明白,也许这是一个简单的问题,这就是为什么jComboBox具有所有元素取自数组channelId而不是Jlist只保存最后一个元素。

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). 每次调用printChannelData()都可以重新创建ListModel (可能在某个循环中)。 Create the ListModel outside, and inside the method just add to the model. 在外部创建ListModel ,并在方法内部添加到模型中。

And channelId is a String[] , but only contains one item. channelId是一个String[] ,但只包含一个项目。 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);   
} 

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

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