e778. adding and removing an item in a jlist component.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 41 行

TXT
41
字号
The default model for a list does not allow the addition and removal of items. The list must be created with a DefaultListModel. 
    // Create a list that allows adds and removes
    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);
    
    // Initialize the list with items
    String[] items = {"A", "B", "C", "D"};
    for (int i=0; i<items.length; i++) {
        model.add(i, items[i]);
    }
    
    // Append an item
    int pos = list.getModel().getSize();
    model.add(pos, "E");
    
    // Insert an item at the beginning
    pos = 0;
    model.add(pos, "a");

This method replaces an item: 
    
    // Replace the 2nd item
    pos = 1;
    model.set(pos, "b");

These methods are used to remove items: 
    
    // Remove the first item
    pos = 0;
    model.remove(pos);
    
    // Remove the last item
    pos = model.getSize()-1;
    if (pos >= 0) {
        model.remove(pos);
    }
    
    // Remove all items
    model.clear();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?